Red Hat Enterprise Linux 7 System Administrator's Guide Administrators En US
User Manual:
Open the PDF directly: View PDF .
Page Count: 533
Download | |
Open PDF In Browser | View PDF |
Red Hat Enterprise Linux 7 System Administrator's Guide Deployment, Configuration, and Administration of Red Hat Enterprise Linux 7 Jaromír Hradílek Stephen Wadeley Miroslav Svoboda Eliška Slobodová David O'Brien Douglas Silas Tomáš Čapek Petr Bokoč Eva Kopalová Michael Hideo Martin Prpič Petr Kovář Peter Ondrejka John Ha Don Domingo Red Hat Enterprise Linux 7 System Administrator's Guide Deployment, Configuration, and Administration of Red Hat Enterprise Linux 7 Jaro mír Hradílek Red Hat Custo mer Co ntent Services jhradilek@redhat.co m Do uglas Silas Red Hat Custo mer Co ntent Services silas@redhat.co m Martin Prpič Red Hat Custo mer Co ntent Services mprpic@redhat.co m Stephen Wadeley Red Hat Custo mer Co ntent Services swadeley@redhat.co m To máš Čapek Red Hat Custo mer Co ntent Services tcapek@redhat.co m Petr Ko vář Red Hat Custo mer Co ntent Services pko var@redhat.co m Miro slav Svo bo da Red Hat Custo mer Co ntent Services msvo bo da@redhat.co m Petr Bo ko č Red Hat Custo mer Co ntent Services pbo ko c@redhat.co m Peter Ondrejka Red Hat Custo mer Co ntent Services po ndrejk@redhat.co m Eliška Slo bo do vá Red Hat Custo mer Co ntent Services Eva Ko palo vá Red Hat Custo mer Co ntent Services Jo hn Ha Red Hat Custo mer Co ntent Services David O'Brien Red Hat Custo mer Co ntent Services Michael Hideo Red Hat Custo mer Co ntent Services Do n Do mingo Red Hat Custo mer Co ntent Services Legal Notice Co pyright © 20 15 Red Hat, Inc. This do cument is licensed by Red Hat under the Creative Co mmo ns Attributio n-ShareAlike 3.0 Unpo rted License. If yo u distribute this do cument, o r a mo dified versio n o f it, yo u must pro vide attributio n to Red Hat, Inc. and pro vide a link to the o riginal. If the do cument is mo dified, all Red Hat trademarks must be remo ved. Red Hat, as the licenso r o f this do cument, waives the right to enfo rce, and agrees no t to assert, Sectio n 4 d o f CC-BY-SA to the fullest extent permitted by applicable law. Red Hat, Red Hat Enterprise Linux, the Shado wman lo go , JBo ss, MetaMatrix, Fedo ra, the Infinity Lo go , and RHCE are trademarks o f Red Hat, Inc., registered in the United States and o ther co untries. Linux ® is the registered trademark o f Linus To rvalds in the United States and o ther co untries. Java ® is a registered trademark o f Oracle and/o r its affiliates. XFS ® is a trademark o f Silico n Graphics Internatio nal Co rp. o r its subsidiaries in the United States and/o r o ther co untries. MySQL ® is a registered trademark o f MySQL AB in the United States, the Euro pean Unio n and o ther co untries. No de.js ® is an o fficial trademark o f Jo yent. Red Hat So ftware Co llectio ns is no t fo rmally related to o r endo rsed by the o fficial Jo yent No de.js o pen so urce o r co mmercial pro ject. The OpenStack ® Wo rd Mark and OpenStack Lo go are either registered trademarks/service marks o r trademarks/service marks o f the OpenStack Fo undatio n, in the United States and o ther co untries and are used with the OpenStack Fo undatio n's permissio n. We are no t affiliated with, endo rsed o r spo nso red by the OpenStack Fo undatio n, o r the OpenStack co mmunity. All o ther trademarks are the pro perty o f their respective o wners. Abstract The System Administrato r's Guide do cuments relevant info rmatio n regarding the deplo yment, co nfiguratio n, and administratio n o f Red Hat Enterprise Linux 7. It is o riented to wards system administrato rs with a basic understanding o f the system. T able of Cont ent s T able of Contents . .art P . . .I.. Basic . . . . . Syst . . . . em . . . Configurat . . . . . . . . . .ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . .hapt C . . . .er . .1. .. Syst . . . . em . . . Locale . . . . . . and . . . . Keyboard . . . . . . . . .Configurat . . . . . . . . . ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . 1.1. Setting the Sys tem Lo c ale 1.2. Chang ing the Keyb o ard Layo ut 1.3. Ad d itio nal Res o urc es 7 9 10 . .hapt C . . . .er . .2. .. Configuring . . . . . . . . . . . t.he . . .Dat . . .e. and . . . . T. ime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. 2. . . . . . . . . . 2 .1. Us ing the timed atec tl Co mmand 12 2 .2. Us ing the d ate Co mmand 15 2 .3. Us ing the hwc lo c k Co mmand 17 2 .4. Ad d itio nal Res o urc es 19 . .hapt C . . . .er . .3. . .Managing . . . . . . . . . Users . . . . . .and ...G . .roups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. 0. . . . . . . . . . 3 .1. Intro d uc tio n to Us ers and G ro up s 3 .2. Manag ing Us ers in a G rap hic al Enviro nment 3 .3. Us ing Co mmand Line To o ls 3 .4. Ad d itio nal Res o urc es 20 21 23 28 . .hapt C . . . .er . .4. .. G . .aining . . . . . .Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 ........... 4 .1. The s u Co mmand 30 4 .2. The s ud o Co mmand 31 4 .3. Ad d itio nal Res o urc es 32 . .art P . . .II.. .Subscript . . . . . . . . ion . . . .and . . . Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 ........... . .hapt C . . . .er . .5. . .Regist . . . . . .ering . . . . .t .he . . Syst . . . . em . . . and . . . . Managing . . . . . . . . . Subscript . . . . . . . . .ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 ........... 5 .1. Reg is tering the Sys tem and Attac hing Sub s c rip tio ns 35 5 .2. Manag ing So ftware Rep o s ito ries 36 5 .3. Remo ving Sub s c rip tio ns 37 5 .4. Ad d itio nal Res o urc es 37 . .hapt C . . . .er . .6. .. Accessing . . . . . . . . . .Support . . . . . . . Using . . . . . . t.he . . .Red . . . .Hat . . . Support . . . . . . . . T. ool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 ........... 6 .1. Ins talling the Red Hat Sup p o rt To o l 39 6 .2. Reg is tering the Red Hat Sup p o rt To o l Us ing the Co mmand Line 39 6 .3. Us ing the Red Hat Sup p o rt To o l in Interac tive Shell Mo d e 39 6 .4. Co nfig uring the Red Hat Sup p o rt To o l 39 6 .5. O p ening and Up d ating Sup p o rt Cas es Us ing Interac tive Mo d e 41 6 .6 . Viewing Sup p o rt Cas es o n the Co mmand Line 43 6 .7. Ad d itio nal Res o urc es 43 . .art P . . .III. . . Inst . . . .alling . . . . .and . . . .Managing . . . . . . . . .Soft . . . .ware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. 4. . . . . . . . . . . .hapt C . . . .er . .7. .. Yum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. 5. . . . . . . . . . 7 .1. Chec king Fo r and Up d ating Pac kag es 45 7 .2. Wo rking with Pac kag es 49 7 .3. Wo rking with Pac kag e G ro up s 58 7 .4. Wo rking with Trans ac tio n His to ry 61 7 .5. Co nfig uring Yum and Yum Rep o s ito ries 67 7 .6 . Yum Plug -ins 78 7 .7. Ad d itio nal Res o urc es 81 . .art P . . .IV. . . Infrast . . . . . . ruct . . . .ure . . . Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8. 2. . . . . . . . . . . .hapt C . . . .er . .8. .. Managing . . . . . . . . . Services . . . . . . . . wit . . .h. syst . . . . emd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8. 3. . . . . . . . . . 1 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 8 .1. Intro d uc tio n to s ys temd 83 8 .2. Manag ing Sys tem Servic es 85 8 .3. Wo rking with s ys temd Targ ets 92 8 .4. Shutting Do wn, Sus p end ing , and Hib ernating the Sys tem 8 .5. Co ntro lling s ys temd o n a Remo te Mac hine 96 98 8 .6 . Creating and Mo d ifying s ys temd Unit Files 8 .7. Ad d itio nal Res o urc es 98 112 . .hapt C . . . .er . .9. .. O . .penSSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. 1. 5. . . . . . . . . . 9 .1. The SSH Pro to c o l 115 9 .2. Co nfig uring O p enSSH 118 9 .3. O p enSSH Clients 126 9 .4. Mo re Than a Sec ure Shell 129 9 .5. Ad d itio nal Res o urc es 130 . .hapt C . . . .er . .1. 0. .. T . .igerVNC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. 32 ........... 10 .1. VNC Server 132 10 .2. VNC Viewer 134 10 .3. Ad d itio nal Res o urc es 137 . .art P . . .V.. .Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. 39 ........... . .hapt C . . . .er . .1. 1. .. Web . . . . Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1.4. 0. . . . . . . . . . 11.1. The Ap ac he HTTP Server 140 . .hapt C . . . .er . .1. 2. .. Mail . . . . Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. 6. 5. . . . . . . . . . 12.1. Email Pro to c o ls 16 5 12.2. Email Pro g ram Clas s ific atio ns 12.3. Mail Trans p o rt Ag ents 16 8 16 9 12.4. Mail Delivery Ag ents 12.5. Mail Us er Ag ents 12.6 . Ad d itio nal Res o urc es 18 1 18 7 18 9 . .hapt C . . . .er . .1. 3. . . Direct . . . . . ory . . . .Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1.9. 1. . . . . . . . . . 13.1. O p enLDAP 19 1 . .hapt C . . . .er . .1. 4. .. File . . . .and . . . .Print . . . . Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2.0. 9. . . . . . . . . . 14.1. Samb a 20 9 14.2. FTP 14.3. Print Setting s 221 227 . .hapt C . . . .er . .1. 5. . . Configuring . . . . . . . . . . . NT . . .P. Using . . . . . . t.he . . .chrony . . . . . . Suit . . . .e. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2.4. 7. . . . . . . . . . 15.1. Intro d uc tio n to the c hro ny Suite 247 15.2. Und ers tand ing c hro ny and Its Co nfig uratio n 248 15.3. Us ing c hro ny 15.4. Setting Up c hro ny fo r Different Enviro nments 254 259 15.5. Us ing c hro nyc 15.6 . Ad d itio nal Res o urc es 26 0 26 1 . .hapt C . . . .er . .1. 6. .. Configuring . . . . . . . . . . . NT . . .P. .Using . . . . . nt . . pd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. 6. 3. . . . . . . . . . 16 .1. Intro d uc tio n to NTP 26 3 2 16 .2. NTP Strata 16 .3. Und ers tand ing NTP 16 .4. Und ers tand ing the Drift File 26 3 26 4 26 5 16 .5. UTC, Timez o nes , and DST 16 .6 . Authentic atio n O p tio ns fo r NTP 26 5 26 5 T able of Cont ent s 16 .6 . Authentic atio n O p tio ns fo r NTP 26 5 16 .7. Manag ing the Time o n Virtual Mac hines 16 .8 . Und ers tand ing Leap Sec o nd s 26 6 26 6 16 .9 . Und ers tand ing the ntp d Co nfig uratio n File 16 .10 . Und ers tand ing the ntp d Sys c o nfig File 26 6 26 8 16 .11. Dis ab ling c hro ny 16 .12. Chec king if the NTP Daemo n is Ins talled 16 .13. Ins talling the NTP Daemo n (ntp d ) 26 8 26 9 26 9 16 .14. Chec king the Status o f NTP 16 .15. Co nfig ure the Firewall to Allo w Inc o ming NTP Pac kets 26 9 26 9 16 .16 . Co nfig ure ntp d ate Servers 16 .17. Co nfig ure NTP 270 271 16 .18 . Co nfig uring the Hard ware Clo c k Up d ate 16 .19 . Co nfig uring Clo c k So urc es 276 277 16 .20 . Ad d itio nal Res o urc es 277 . .hapt C . . . .er . .1. 7. .. Configuring . . . . . . . . . . . PT . . .P. Using . . . . . . pt . . p4 . . l. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2.7. 9. . . . . . . . . . 17.1. Intro d uc tio n to PTP 17.2. Us ing PTP 17.3. Sp ec ifying a Co nfig uratio n File 279 28 1 28 4 17.4. Us ing the PTP Manag ement Client 17.5. Sync hro niz ing the Clo c ks 28 4 28 5 17.6 . Verifying Time Sync hro niz atio n 17.7. Serving PTP Time with NTP 28 6 28 8 17.8 . Serving NTP Time with PTP 17.9 . Sync hro niz e to PTP o r NTP Time Us ing timemas ter 28 8 28 9 17.10 . Imp ro ving Ac c urac y 17.11. Ad d itio nal Res o urc es 29 2 29 3 . .art P . . .VI. . . Monit . . . . . oring . . . . . .and . . . Aut . . . .omat . . . . ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2.9. 4. . . . . . . . . . . .hapt C . . . .er . .1. 8. .. Syst . . . . em . . . Monit . . . . . oring . . . . . .T.ools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. 9. 5. . . . . . . . . . 18 .1. Viewing Sys tem Pro c es s es 29 5 18 .2. Viewing Memo ry Us ag e 18 .3. Viewing CPU Us ag e 29 8 29 9 18 .4. Viewing Blo c k Devic es and File Sys tems 18 .5. Viewing Hard ware Info rmatio n 30 0 30 5 18 .6 . Mo nito ring Perfo rmanc e with Net-SNMP 18 .7. Ad d itio nal Res o urc es 30 7 321 . .hapt C . . . .er . .1. 9. .. O . .penLMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32 . . 2. . . . . . . . . . 19 .1. Ab o ut O p enLMI 322 19 .2. Ins talling O p enLMI 323 19 .3. Co nfig uring SSL Certific ates fo r O p enPeg as us 324 19 .4. Us ing LMIShell 19 .5. Us ing O p enLMI Sc rip ts 19 .6 . Ad d itio nal Res o urc es 329 36 7 36 7 . .hapt C . . . .er . .2. 0. .. Viewing . . . . . . . .and . . . Managing . . . . . . . . . .Log . . . Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36 . . 9. . . . . . . . . . 2 0 .1. Lo c ating Lo g Files 36 9 2 0 .2. Bas ic Co nfig uratio n o f Rs ys lo g 36 9 2 0 .3. Wo rking with Q ueues in Rs ys lo g 38 5 2 0 .4. Co nfig uring rs ys lo g o n a Lo g g ing Server 2 0 .5. Us ing Rs ys lo g Mo d ules 2 0 .6 . Interac tio n o f Rs ys lo g and Jo urnal 2 0 .7. Struc tured Lo g g ing with Rs ys lo g 39 2 39 3 39 6 39 7 3 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 2 0 .7. Struc tured Lo g g ing with Rs ys lo g 39 7 2 0 .8 . Deb ug g ing Rs ys lo g 2 0 .9 . Us ing the Jo urnal 2 0 .10 . Manag ing Lo g Files in a G rap hic al Enviro nment 2 0 .11. Ad d itio nal Res o urc es 40 0 40 0 40 6 411 . .hapt C . . . .er . .2. 1. .. Aut . . . omat . . . . .ing . . . Syst . . . . em . . .T . .asks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. 1. 3. . . . . . . . . . 2 1.1. Cro n and Anac ro n 413 2 1.2. At and Batc h 418 2 1.3. Ad d itio nal Res o urc es 422 . .hapt C . . . .er . .2. 2. .. Aut . . . omat . . . . .ic . .Bug . . . . Report . . . . . . ing . . . .T.ool . . . (ABRT . . . . . .). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. 2. 3. . . . . . . . . . 2 2.1. Intro d uc tio n to ABRT 2 2.2. Ins talling ABRT and Starting its Servic es 2 2.3. Co nfig uring ABRT 2 2.4. Detec ting So ftware Pro b lems 2 2.5. Hand ling Detec ted Pro b lems 423 423 425 432 434 2 2.6 . Ad d itio nal Res o urc es 436 . .hapt C . . . .er . .2. 3. . .O . .Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. 38 ........... 2 3.1. O verview o f To o ls 2 3.2. Us ing o p erf 2 3.3. Co nfig uring O Pro file Us ing Leg ac y Mo d e 2 3.4. Starting and Sto p p ing O Pro file Us ing Leg ac y Mo d e 438 439 442 447 2 3.5. Saving Data in Leg ac y Mo d e 2 3.6 . Analyz ing the Data 2 3.7. Und ers tand ing the /d ev/o p ro file/ d irec to ry 2 3.8 . Examp le Us ag e 2 3.9 . O Pro file Sup p o rt fo r Java 448 448 453 454 454 2 3.10 . G rap hic al Interfac e 2 3.11. O Pro file and Sys temTap 2 3.12. Ad d itio nal Res o urc es 455 458 458 . .art P . . .VII. . . .Kernel, . . . . . . Module . . . . . . . and . . . . Driver . . . . . .Configurat . . . . . . . . . ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4.6. 0. . . . . . . . . . . .hapt C . . . .er . .2. 4. .. Working . . . . . . . .wit ..h . . t.he . . .G. RUB . . . . .2. Boot . . . . . Loader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4.6. 1. . . . . . . . . . 2 4.1. Co nfig uring the G RUB 2 Bo o t Lo ad er 46 1 2 4.2. Cus to miz ing G RUB 2 Menu 46 2 2 4.3. G RUB 2 Pas s wo rd Pro tec tio n 46 7 2 4.4. Reins talling G RUB 2 46 9 2 4.5. G RUB 2 o ver Serial Co ns o le 2 4.6 . Terminal Menu Ed iting During Bo o t 2 4.7. Unified Extens ib le Firmware Interfac e (UEFI) Sec ure Bo o t 2 4.8 . Ad d itio nal Res o urc es 470 471 475 476 . .hapt C . . . .er . .2. 5. . . Manually . . . . . . . . Upgrading . . . . . . . . . . t. he . . .Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4.7. 8. . . . . . . . . . 2 5.1. O verview o f Kernel Pac kag es 478 2 5.2. Prep aring to Up g rad e 479 2 5.3. Do wnlo ad ing the Up g rad ed Kernel 2 5.4. Perfo rming the Up g rad e 2 5.5. Verifying the Initial RAM Dis k Imag e 2 5.6 . Verifying the Bo o t Lo ad er 48 0 48 0 48 1 48 3 . .hapt C . . . .er . .2. 6. .. Working . . . . . . . .wit ..h . . Kernel . . . . . . Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. 8. 5. . . . . . . . . . 2 6 .1. Lis ting Currently-Lo ad ed Mo d ules 48 5 2 6 .2. Dis p laying Info rmatio n Ab o ut a Mo d ule 4 48 6 T able of Cont ent s 2 6 .2. Dis p laying Info rmatio n Ab o ut a Mo d ule 2 6 .3. Lo ad ing a Mo d ule 2 6 .4. Unlo ad ing a Mo d ule 2 6 .5. Setting Mo d ule Parameters 2 6 .6 . Pers is tent Mo d ule Lo ad ing 48 6 48 9 49 0 49 1 49 2 2 6 .7. Sig ning Kernel Mo d ules fo r Sec ure Bo o t 2 6 .8 . Ad d itio nal Res o urc es 49 2 49 8 .RPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50 . . 0. . . . . . . . . . A .1. RPM Des ig n G o als 50 0 A .2. Us ing RPM 50 1 A .3. Find ing and Verifying RPM Pac kag es 50 7 A .4. Co mmo n Examp les o f RPM Us ag e 50 8 A .5. Ad d itio nal Res o urc es 50 9 . . . . . . . . .Hist Revision . . . ory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51 . . 0. . . . . . . . . . B .1. Ac kno wled g ments 510 I.ndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51 . . 0. . . . . . . . . . 5 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Part I. Basic System Configuration This part covers basic system administration tasks such as keyboard configuration, date and time configuration, managing users and groups, and gaining privileges. 6 Chapt er 1 . Syst em Locale and Keyboard Configurat ion Chapter 1. System Locale and Keyboard Configuration The system locale specifies the language settings of system services and user interfaces. The keyboard layout settings control the layout used on the text console and graphical user interfaces. These settings can be made by modifying the /etc/l o cal e. co nf configuration file or by using the lo calect l utility. Also, you can use the graphical user interface to perform the task; for a description of this method, see Red Hat Enterprise Linux 7 Installation Guide. 1.1. Set t ing t he Syst em Locale System-wide locale settings are stored in the /etc/l o cal e. co nf file, which is read at early boot by the systemd daemon. The locale settings configured in /etc/l o cal e. co nf are inherited by every service or user, unless individual programs or individual users override them. The basic file format of /etc/l o cal e. co nf is a newline-separated list of variable assignments. For example, German locale with English messages in /etc/l o cal e. co nf looks as follows: LANG=de_DE.UTF-8 LC_MESSAGES=C Here, the LC_MESSAGES option determines the locale used for diagnostic messages written to the standard error output. To further specify locale settings in /etc/l o cal e. co nf, you can use several other options, the most relevant are summarized in Table 1.1, “ Options configurable in /etc/locale.conf” . See the l o cal e(7) manual page for detailed information on these options. Note that the LC_ALL option, which represents all possible options, should not be configured in /etc/l o cal e. co nf. T ab le 1.1. O p t io n s co n f ig u rab le in /et c/lo cale.co n f O p t io n D escrip t io n LANG LC_COLLATE Provides a default value for the system locale. Changes the behavior of functions which compare strings in the local alphabet. Changes the behavior of the character handling and classification functions and the multibyte character functions. D escribes the way numbers are usually printed, with details such as decimal point versus decimal comma. Changes the display of the current time, 24-hour versus 12-hour clock. D etermines the locale used for diagnostic messages written to the standard error output. LC_CTYPE LC_NUMERIC LC_TIME LC_MESSAGES 1.1.1. Displaying t he Current St at us The l o cal ectl command can be used to query and change the system locale and keyboard layout settings. To show the current settings, use the status option: l o cal ectl status 7 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Examp le 1.1. D isp layin g t h e C u rren t St at u s The output of the previous command lists the currently set locale, keyboard layout configured for the console and for the X11 window system. ~]$ l o cal ectl status System Locale: LANG=en_US.UTF-8 VC Keymap: us X11 Layout: n/a 1.1.2. List ing Available Locales To list all locales available for your system, type: l o cal ectl l i st-l o cal es Examp le 1.2. List in g Lo cales Imagine you want to select a specific English locale, but you are not sure if it is available on the system. You can check that by listing all English locales with the following command: ~]$ l o cal ectl l i st-l o cal es | g rep en_ en_AG en_AG.utf8 en_AU en_AU.iso88591 en_AU.utf8 en_BW en_BW.iso88591 en_BW.utf8 output truncated 1.1.3. Set t ing t he Locale To set the default system locale, use the following command as ro o t: l o cal ectl set-l o cal e LANG =locale Replace locale with the locale name, found with the l o cal ectl l i st-l o cal es command. The above syntax can also be used to configure parameters from Table 1.1, “ Options configurable in /etc/locale.conf” . Examp le 1.3. C h an g in g t h e D ef au lt Lo cale For example, if you want to set British English as your default locale, first find the name of this locale by using l i st-l o cal es. Then, as ro o t, type the command in the following form: ~]# l o cal ectl set-l o cal e LANG =en_G B. utf8 8 Chapt er 1 . Syst em Locale and Keyboard Configurat ion 1.2. Changing t he Keyboard Layout The keyboard layout settings enable the user to control the layout used on the text console and graphical user interfaces. 1.2.1. Displaying t he Current Set t ings As mentioned before, you can check your current keyboard layout configuration with the following command: l o cal ectl status Examp le 1.4 . D isp layin g t h e K eyb o ard Set t in g s In the following output, you can see the keyboard layout configured for the virtual console and for the X11 window system. ~]$ l o cal ectl status System Locale: LANG=en_US.utf8 VC Keymap: us X11 Layout: us 1.2.2. List ing Available Keymaps To list all available keyboard layouts that can be configured on your system, type: l o cal ectl l i st-keymaps Examp le 1.5. Search in g f o r a Part icu lar K eymap You can use g rep to search the output of the previous command for a specific keymap name. There are often multiple keymaps compatible with your currently set locale. For example, to find available Czech keyboard layouts, type: ~]$ l o cal ectl l i st-keymaps | g rep cz cz cz-cp1250 cz-lat2 cz-lat2-prog cz-qwerty cz-us-qwertz sunt5-cz-us sunt5-us-cz 1.2.3. Set t ing t he Keymap 9 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To set the default keyboard layout for your system, use the following command as ro o t: l o cal ectl set-keymap map Replace map with the name of the keymap taken from the output of the l o cal ectl l i st-keymaps command. Unless the --no -co nvert option is passed, the selected setting is also applied to the default keyboard mapping of the X11 window system, after converting it to the closest matching X11 keyboard mapping. This also applies in reverse, you can specify both keymaps with the following command as ro o t: l o cal ectl set-x11-keymap map If you want your X11 layout to differ from the console layout, use the --no -co nvert option. l o cal ectl --no -co nvert set-x11-keymap map With this option, the X11 keymap is specified without changing the previous console layout setting. Examp le 1.6 . Set t in g t h e X11 K eymap Sep arat ely Imagine you want to use German keyboard layout in the graphical interface, but for console operations you want to retain the US keymap. To do so, type as ro o t: ~]# l o cal ectl --no -co nvert set-x11-keymap de Then you can verify if your setting was successful by checking the current status: ~]$ l o cal ectl status System Locale: LANG=de_DE.UTF-8 VC Keymap: us X11 Layout: de Apart from keyboard layout (map), three other options can be specified: l o cal ectl set-x11-keymap map model variant options Replace model with the keyboard model name, variant and options with keyboard variant and option components, which can be used to enhance the keyboard behavior. These options are not set by default. For more information on X11 Model, X11 Variant, and X11 Options see the kbd (4 ) man page. 1.3. Addit ional Resources For more information on how to configure the keyboard layout on Red Hat Enterprise Linux, see the resources listed below: Inst alled Document at ion l o cal ectl (1) — The manual page for the l o cal ectl command line utility documents how to use this tool to configure the system locale and keyboard layout. 10 Chapt er 1 . Syst em Locale and Keyboard Configurat ion l o ad keys(1) — The manual page for the l o ad keys command provides more information on how to use this tool to change the keyboard layout in a virtual console. See Also Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. Chapter 8, Managing Services with systemd provides more information on systemd and documents how to use the systemctl command to manage system services. 11 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 2. Configuring the Date and Time Modern operating systems distinguish between the following two types of clocks: A real-time clock (RTC), commonly referred to as a hardware clock, (typically an integrated circuit on the system board) that is completely independent of the current state of the operating system and runs even when the computer is shut down. A system clock, also known as a software clock, that is maintained by the kernel and its initial value is based on the real-time clock. Once the system is booted and the system clock is initialized, the system clock is completely independent of the real-time clock. The system time is always kept in Coordinated Universal Time (UTC) and converted in applications to local time as needed. Local time is the actual time in your current time zone, taking into account daylight saving time (D ST). The real-time clock can use either UTC or local time. UTC is recommended. Red Hat Enterprise Linux 7 offers three command line tools that can be used to configure and display information about the system date and time: the ti med atectl utility, which is new in Red Hat Enterprise Linux 7 and is part of systemd ; the traditional d ate command; and the hwcl o ck utility for accessing the hardware clock. 2.1. Using t he t imedat ect l Command The t imed at ect l utility is distributed as part of the systemd system and service manager and allows you to review and change the configuration of the system clock. You can use this tool to change the current date and time, set the time zone, or enable automatic synchronization of the system clock with a remote server. For information on how to display the current date and time in a custom format, see also Section 2.2, “ Using the date Command” . 2.1.1. Displaying t he Current Dat e and T ime To display the current date and time along with detailed information about the configuration of the system and hardware clock, run the ti med atectl command with no additional command line options: ti med atectl This displays the local and universal time, the currently used time zone, the status of the Network Time Protocol (NT P ) configuration, and additional information related to D ST. Examp le 2.1. D isp layin g t h e C u rren t D at e an d T ime The following is an example output of the ti med atectl command on a system that does not use NT P to synchronize the system clock with a remote server: ~]$ ti med atectl Local time: Universal time: Timezone: NTP enabled: NTP synchronized: RTC in local TZ: 12 Mon 2013-09-16 19:30:24 CEST Mon 2013-09-16 17:30:24 UTC Europe/Prague (CEST, +0200) no no no Chapt er 2 . Configuring t he Dat e and T ime DST active: yes Last DST change: DST Sun Sun Next DST change: DST Sun Sun began at 2013-03-31 01:59:59 CET 2013-03-31 03:00:00 CEST ends (the clock jumps one hour backwards) at 2013-10-27 02:59:59 CEST 2013-10-27 02:00:00 CET 2.1.2. Changing t he Current T ime To change the current time, type the following at a shell prompt as ro o t: ti med atectl set-ti me HH:MM:SS Replace HH with an hour, MM with a minute, and SS with a second, all typed in two-digit form. This command updates both the system time and the hardware clock. The result it is similar to using both the d ate --set and hwcl o ck --systo hc commands. Examp le 2.2. C h an g in g t h e C u rren t T ime To change the current time to 11:26 p.m., run the following command as ro o t: ~]# ti med atectl set-ti me 23: 26 : 0 0 By default, the system is configured to use UTC. To configure your system to maintain the clock in the local time, run the ti med atectl command with the set-l o cal -rtc option as ro o t: ti med atectl set-l o cal -rtc boolean To configure your system to maintain the clock in the local time, replace boolean with yes (or, alternatively, y, true, t, or 1). To configure the system to use UTC, replace boolean with no (or, alternatively, n, fal se, f, or 0 ). The default option is no . 2.1.3. Changing t he Current Dat e To change the current date, type the following at a shell prompt as ro o t: ti med atectl set-ti me YYYY-MM-DD Replace YYYY with a four-digit year, MM with a two-digit month, and DD with a two-digit day of the month. Note that changing the date without specifying the current time results in setting the time to 00:00:00. Examp le 2.3. C h an g in g t h e C u rren t D at e To change the current date to 2 June 2013 and keep the current time (11:26 p.m.), run the following command as ro o t: 13 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# ti med atectl set-ti me ' 20 13-0 6 -0 2 23: 26 : 0 0 ' 2.1.4 . Changing t he T ime Zone To list all available time zones, type the following at a shell prompt: ti med atectl l i st-ti mezo nes To change the currently used time zone, type as ro o t: ti med atectl set-ti mezo ne time_zone Replace time_zone with any of the values listed by the ti med atectl l i st-ti mezo nes command. Examp le 2.4 . C h an g in g t h e T ime Z o n e To identify which time zone is closest to your present location, use the ti med atectl command with the l i st-ti mezo nes command line option. For example, to list all available time zones in Europe, type: ~]# ti med atectl l i st-ti mezo nes | g rep Euro pe Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belgrade Europe/Berlin Europe/Bratislava … To change the time zone to Euro pe/P rag ue, type as ro o t: ~]# ti med atectl set-ti mezo ne Euro pe/P rag ue 2.1.5. Synchroniz ing t he Syst em Clock wit h a Remot e Server As opposed to the manual setup described in the previous sections, the ti med atectl command also allows you to enable automatic synchronization of your system clock with a group of remote servers using NT P . Enabling NTP enables the chro nyd or ntpd service, depending on which of them is installed. To enable or disable NTP, type the following at a shell prompt as ro o t: ti med atectl set-ntp boolean To configure your system to synchronize the system clock with a remote NT P server, replace boolean with yes (the default option). To disable this feature, replace boolean with no . Examp le 2.5. Syn ch ro n iz in g t h e Syst em C lo ck wit h a R emo t e Server 14 Chapt er 2 . Configuring t he Dat e and T ime To enable automatic synchronization of the system clock with a remote server, type: ~]# ti med atectl set-ntp yes 2.2. Using t he dat e Command The d ate utility is available on all Linux systems and allows you to display and configure the current date and time. It is frequently used in scripts to display detailed information about the system clock in a custom format. For information on how to change the time zone or enable automatic synchronization of the system clock with a remote server, see Section 2.1, “ Using the timedatectl Command” . 2.2.1. Displaying t he Current Dat e and T ime To display the current date and time, run the d ate command with no additional command line options: d ate This displays the day of the week followed by the current date, local time, abbreviated time zone, and year. By default, the d ate command displays the local time. To display the time in UTC, run the command with the --utc or -u command line option: d ate --utc You can also customize the format of the displayed information by providing the + "format" option on the command line: d ate + "format" Replace format with one or more supported control sequences as illustrated in Example 2.6, “ D isplaying the Current D ate and Time” . See Table 2.1, “ Commonly Used Control Sequences” for a list of the most frequently used formatting options, or the d ate(1) manual page for a complete list of these options. T ab le 2.1. C o mmo n ly U sed C o n t ro l Seq u en ces C o n t ro l Seq u en ce D escrip t io n %H %M %S %d %m %Y %Z %F The hour in the HH format (for example, 17). The minute in the MM format (for example, 30 ). The second in the SS format (for example, 24 ). The day of the month in the DD format (for example, 16 ). The month in the MM format (for example, 0 9 ). The year in the YYYY format (for example, 20 13). The time zone abbreviation (for example, C EST ). The full date in the YYYY-MM-DD format (for example, 20 13-0 9 -16 ). This option is equal to %Y -%m-%d . 15 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide C o n t ro l Seq u en ce D escrip t io n %T The full time in the HH:MM:SS format (for example, 17:30:24). This option is equal to %H: %M: %S Examp le 2.6 . D isp layin g t h e C u rren t D at e an d T ime To display the current date and local time, type the following at a shell prompt: ~]$ d ate Mon Sep 16 17:30:24 CEST 2013 To display the current date and time in UTC, type the following at a shell prompt: ~]$ d ate --utc Mon Sep 16 15:30:34 UTC 2013 To customize the output of the d ate command, type: ~]$ d ate + "%Y -%m-%d %H: %M" 2013-09-16 17:30 2.2.2. Changing t he Current T ime To change the current time, run the d ate command with the --set or -s option as ro o t: d ate --set HH:MM:SS Replace HH with an hour, MM with a minute, and SS with a second, all typed in two-digit form. By default, the d ate command sets the system clock to the local time. To set the system clock in UTC, run the command with the --utc or -u command line option: d ate --set HH:MM:SS --utc Examp le 2.7. C h an g in g t h e C u rren t T ime To change the current time to 11:26 p.m., run the following command as ro o t: ~]# d ate --set 23: 26 : 0 0 2.2.3. Changing t he Current Dat e To change the current date, run the d ate command with the --set or -s option as ro o t: d ate --set YYYY-MM-DD Replace YYYY with a four-digit year, MM with a two-digit month, and DD with a two-digit day of the month. 16 Chapt er 2 . Configuring t he Dat e and T ime Note that changing the date without specifying the current time results in setting the time to 00:00:00. Examp le 2.8. C h an g in g t h e C u rren t D at e To change the current date to 2 June 2013 and keep the current time (11:26 p.m.), run the following command as ro o t: ~]# d ate --set 20 13-0 6 -0 2 23: 26 : 0 0 2.3. Using t he hwclock Command hwcl o ck is a utility for accessing the hardware clock, also referred to as the Real Time Clock (RTC). The hardware clock is independent of the operating system you use and works even when the machine is shut down. This utility is used for displaying the time from the hardware clock. hwcl o ck also contains facilities for compensating for systematic drift in the hardware clock. The hardware clock stores the values of: year, month, day, hour, minute, and second. It is not able to store the time standard, local time or Coordinated Universal Time (UTC), nor set the D aylight Saving Time (D ST). The hwcl o ck utility saves its settings in the /etc/ad jti me file, which is created with the first change you make, for example, when you set the time manually or synchronize the hardware clock with the system time. Note In Red Hat Enterprise Linux 6, the hwcl o ck command was run automatically on every system shutdown or reboot, but it is not in Red Hat Enterprise Linux 7. When the system clock is synchronized by the Network Time Protocol (NTP) or Precision Time Protocol (PTP), the kernel automatically synchronizes the hardware clock to the system clock every 11 minutes. For details about NTP, see Chapter 15, Configuring NTP Using the chrony Suite and Chapter 16, Configuring NTP Using ntpd. For information about PTP, see Chapter 17, Configuring PTP Using ptp4l. For information about setting the hardware clock after executing n t p d at e, see Section 16.18, “ Configuring the Hardware Clock Update” . 2.3.1. Displaying t he Current Dat e and T ime Running hwcl o ck with no command line options as the ro o t user returns the date and time in local time to standard output. hwcl o ck Note that using the --utc or --l o cal ti me options with the hwcl o ck command does not mean you are displaying the hardware clock time in UTC or local time. These options are used for setting the hardware clock to keep time in either of them. The time is always displayed in local time. Additionally, using the hwcl o ck --utc or hwcl o ck --l o cal commands does not change the 17 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide record in the /etc/ad jti me file. This command can be useful when you know that the setting saved in /etc/ad jti me is incorrect but you do not want to change the setting. On the other hand, you may receive misleading information if you use the command an incorrect way. See the hwcl o ck(8) manual page for more details. Examp le 2.9 . D isp layin g t h e C u rren t D at e an d T ime To display the current date and the current local time from the hardware clock, run as ro o t: ~]# hwcl o ck Tue 15 Apr 2014 04:23:46 PM CEST -0.329272 seconds CEST is a time zone abbreviation and stands for Central European Summer Time. For information on how to change the time zone, see Section 2.1.4, “ Changing the Time Z one” . 2.3.2. Set t ing t he Dat e and T ime Besides displaying the date and time, you can manually set the hardware clock to a specific time. When you need to change the hardware clock date and time, you can do so by appending the --set and --d ate options along with your specification: hwcl o ck --set --d ate "dd mmm yyyy HH:MM" Replace dd with a day (a two-digit number), mmm with a month (a three-letter abbreviation), yyyy with a year (a four-digit number), HH with an hour (a two-digit number), MM with a minute (a two-digit number). At the same time, you can also set the hardware clock to keep the time in either UTC or local time by adding the --utc or --l o cal ti me options, respectively. In this case, UT C or LO C AL is recorded in the /etc/ad jti me file. Examp le 2.10. Set t in g t h e H ard ware C lo ck t o a Sp ecif ic D at e an d T ime If you want to set the date and time to a specific value, for example, to " 21:17, October 21, 2014" , and keep the hardware clock in UTC, run the command as ro o t in the following format: ~]# hwcl o ck --set --d ate "21 O ct 20 14 21: 17" --utc 2.3.3. Synchroniz ing t he Dat e and T ime You can synchronize the hardware clock and the current system time in both directions. Either you can set the hardware clock to the current system time by using this command: hwcl o ck --systo hc Note that if you use NTP, the hardware clock is automatically synchronized to the system clock every 11 minutes, and this command is useful only at boot time to get a reasonable initial system time. 18 Chapt er 2 . Configuring t he Dat e and T ime Or, you can set the system time from the hardware clock by using the following command: hwcl o ck --hcto sys When you synchronize the hardware clock and the system time, you can also specify whether you want to keep the hardware clock in local time or UTC by adding the --utc or --l o cal ti me option. Similarly to using --set, UT C or LO C AL is recorded in the /etc/ad jti me file. The hwcl o ck --systo hc --utc command is functionally similar to ti med atectl set-l o cal rtc fal se and the hwcl o ck --systo hc --l o cal command is an alternative to ti med atectl set-l o cal -rtc true. Examp le 2.11. Syn ch ro n iz in g t h e H ard ware C lo ck wit h Syst em T ime To set the hardware clock to the current system time and keep the hardware clock in local time, run the following command as ro o t: ~]# hwcl o ck --systo hc --l o cal ti me To avoid problems with time zone and D ST switching, it is recommended to keep the hardware clock in UTC. The shown Example 2.11, “ Synchronizing the Hardware Clock with System Time” is useful, for example, in case of a multi boot with a Windows system, which assumes the hardware clock runs in local time by default, and all other systems need to accommodate to it by using local time as well. It may also be needed with a virtual machine; if the virtual hardware clock provided by the host is running in local time, the guest system needs to be configured to use local time, too. 2.4 . Addit ional Resources For more information on how to configure the date and time in Red Hat Enterprise Linux 7, see the resources listed below. Inst alled Document at ion ti med atectl (1) — The manual page for the ti med atectl command line utility documents how to use this tool to query and change the system clock and its settings. d ate(1) — The manual page for the d ate command provides a complete list of supported command line options. hwcl o ck(8) — The manual page for the hwcl o ck command provides a complete list of supported command line options. See Also Chapter 1, System Locale and Keyboard Configuration documents how to configure the keyboard layout. Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. Chapter 8, Managing Services with systemd provides more information on systemd and documents how to use the systemctl command to manage system services. 19 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 3. Managing Users and Groups The control of users and groups is a core element of Red Hat Enterprise Linux system administration. This chapter explains how to add, manage, and delete users and groups in the graphical user interface and on the command line, and covers advanced topics, such as creating group directories. 3.1. Int roduct ion t o Users and Groups While users can be either people (meaning accounts tied to physical users) or accounts which exist for specific applications to use, groups are logical expressions of organization, tying users together for a common purpose. Users within a group share the same permissions to read, write, or execute files owned by that group. Each user is associated with a unique numerical identification number called a user ID (UID ). Likewise, each group is associated with a group ID (GID ). A user who creates a file is also the owner and group owner of that file. The file is assigned separate read, write, and execute permissions for the owner, the group, and everyone else. The file owner can be changed only by ro o t, and access permissions can be changed by both the ro o t user and file owner. Additionally, Red Hat Enterprise Linux supports access control lists (ACLs) for files and directories which allow permissions for specific users outside of the owner to be set. For more information about this feature, see the Access Control Lists chapter of the Storage Administration Guide. 3.1.1. User Privat e Groups Red Hat Enterprise Linux uses a user private group (UPG) scheme, which makes UNIX groups easier to manage. A user private group is created whenever a new user is added to the system. It has the same name as the user for which it was created and that user is the only member of the user private group. User private groups make it safe to set default permissions for a newly created file or directory, allowing both the user and the group of that user to make modifications to the file or directory. The setting which determines what permissions are applied to a newly created file or directory is called a umask and is configured in the /etc/bashrc file. Traditionally on UNIX-based systems, the umask is set to 0 22, which allows only the user who created the file or directory to make modifications. Under this scheme, all other users, including members of the creator's group, are not allowed to make any modifications. However, under the UPG scheme, this “ group protection” is not necessary since every user has their own private group. A list of all groups is stored in the /etc/g ro up configuration file. 3.1.2. Shadow Passwords In environments with multiple users, it is very important to use shadow passwords provided by the shadow-utils package to enhance the security of system authentication files. For this reason, the installation program enables shadow passwords by default. The following is a list of the advantages shadow passwords have over the traditional way of storing passwords on UNIX-based systems: Shadow passwords improve system security by moving encrypted password hashes from the world-readable /etc/passwd file to /etc/shad o w, which is readable only by the ro o t user. Shadow passwords store information about password aging. Shadow passwords allow the /etc/l o g i n. d efs file to enforce security policies. 20 Chapt er 3. Managing Users and G roups Most utilities provided by the shadow-utils package work properly whether or not shadow passwords are enabled. However, since password aging information is stored exclusively in the /etc/shad o w file, some utilities and commands do not work without first enabling shadow passwords: The chag e utility for setting password-aging parameters. For details, see the Password Security section in the Red Hat Enterprise Linux 7 Security Guide. The g passwd utility for administrating the /etc/g ro up file. The usermo d command with the -e, --expi red ate or -f, --i nacti ve option. The userad d command with the -e, --expi red ate or -f, --i nacti ve option. 3.2. Managing Users in a Graphical Environment The U sers utility allows you to view, modify, add, and delete local users in the graphical user interface. 3.2.1. Using t he Users Set t ings T ool Press the Super key to enter the Activities Overview, type Users and then press Enter. The U sers settings tool appears. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. Alternatively, you can open the U sers utility from the Set t in g s menu after clicking your user name in the top right corner of the screen. To make changes to the user accounts, first select the Unl o ck button and authenticate yourself as indicated by the dialog box that appears. Note that unless you have superuser privileges, the application will prompt you to authenticate as ro o t. To add and remove users, select the + and button respectively. To add a user to the administrative group wheel , change the Acco u n t T yp e from Stand ard to Ad mi ni strato r. To edit a user's language setting, select the language and a drop-down menu appears. 21 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 3.1. T h e U sers Set t in g s T o o l When a new user is created, the account is disabled until a password is set. The Passwo rd dropdown menu, shown in Figure 3.2, “ The Password Menu” , contains the options to set a password by the administrator immediately, choose a password by the user at the first login, or create a guest account with no password required to log in. You can also disable or enable an account from this menu. 22 Chapt er 3. Managing Users and G roups Fig u re 3.2. T h e Passwo rd Men u 3.3. Using Command Line T ools Apart from the U sers settings tool described in Section 3.2, “ Managing Users in a Graphical Environment” , which is designed for basic managing of users, you can use command line tools for managing users and groups that are listed in Table 3.1, “ Command line utilities for managing users and groups” . T ab le 3.1. C o mman d lin e u t ilit ies f o r man ag in g u sers an d g ro u p s U t ilit ies D escrip t io n id userad d , usermo d , userd el D isplays user and group ID s. Standard utilities for adding, modifying, and deleting user accounts. Standard utilities for adding, modifying, and deleting groups. g ro upad d , g ro upmo d , g ro upd el g passwd pwck, g rpck pwco nv, pwunco nv g rpco nv, g rpunco nv Standard utility for administering the /etc/g ro up configuration file. Utilities that can be used for verification of the password, group, and associated shadow files. Utilities that can be used for the conversion of passwords to shadow passwords, or back from shadow passwords to standard passwords. Similar to the previous, these utilities can be used for conversion of shadowed information for group accounts. 23 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 3.3.1. Adding a New User To add a new user to the system, type the following at a shell prompt as ro o t: userad d [options] username …where options are command-line options as described in Table 3.2, “ Common useradd commandline options” . By default, the userad d command creates a locked user account. To unlock the account, run the following command as ro o t to assign a password: passwd username Optionally, you can set a password aging policy. See the Password Security section in the Red Hat Enterprise Linux 7 Security Guide. T ab le 3.2. C o mmo n u serad d co mman d - lin e o p t io n s O p t io n D escrip t io n -c 'comment' comment can be replaced with any string. This option is generally used to specify the full name of a user. Home directory to be used instead of default /ho me/username/. D ate for the account to be disabled in the format YYYY-MM-D D . Number of days after the password expires until the account is disabled. If 0 is specified, the account is disabled immediately after the password expires. If -1 is specified, the account is not disabled after the password expires. Group name or group number for the user's default (primary) group. The group must exist prior to being specified here. List of additional (supplementary, other than default) group names or group numbers, separated by commas, of which the user is a member. The groups must exist prior to being specified here. Create the home directory if it does not exist. D o not create the home directory. D o not create a user private group for the user. The password encrypted with crypt. Create a system account with a UID less than 1000 and without a home directory. User's login shell, which defaults to /bi n/bash. User ID for the user, which must be unique and greater than 999. -d home_directory -e date -f days -g group_name -G group_list -m -M -N -p password -r -s -u uid The command-line options associated with the usermo d command are essentially the same. Note that if you want to add a user to another supplementary group, you need to use the -a, --append option with the -G option. Otherwise the list of supplementary groups for the user will be overwritten by those specified with the usermo d -G command. 24 Chapt er 3. Managing Users and G roups Important The default range of ID s for system and regular users has been changed in Red Hat Enterprise Linux 7 from the earlier releases. Previously, UID 1-499 was used for system users and values above for regular users. This change might cause problems when migrating to Red Hat Enterprise Linux 7 with existing users having UID s and GID s between 500 and 999. The default ranges of UID and GID can be changed in the /etc/l o g i n. d efs file. Explaining t he Pro ce ss The following steps illustrate what happens if the command userad d juan is issued on a system that has shadow passwords enabled: 1. A new line for juan is created in /etc/passwd : juan:x:1001:1001::/home/juan:/bin/bash The line has the following characteristics: It begins with the user name juan. There is an x for the password field indicating that the system is using shadow passwords. A UID greater than 999 is created. Under Red Hat Enterprise Linux 7, UID s below 1000 are reserved for system use and should not be assigned to users. A GID greater than 999 is created. Under Red Hat Enterprise Linux 7, GID s below 1000 are reserved for system use and should not be assigned to users. The optional GECOS information is left blank. The GECOS field can be used to provide additional information about the user, such as their full name or phone number. The home directory for juan is set to /ho me/juan/. The default shell is set to /bi n/bash. 2. A new line for juan is created in /etc/shad o w: juan:!!:14798:0:99999:7::: The line has the following characteristics: It begins with the username juan. Two exclamation marks (! ! ) appear in the password field of the /etc/shad o w file, which locks the account. Note If an encrypted password is passed using the -p flag, it is placed in the /etc/shad o w file on the new line for the user. 25 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The password is set to never expire. 3. A new line for a group named juan is created in /etc/g ro up: juan:x:1001: A group with the same name as a user is called a user private group. For more information on user private groups, see Section 3.1.1, “ User Private Groups” . The line created in /etc/g ro up has the following characteristics: It begins with the group name juan. An x appears in the password field indicating that the system is using shadow group passwords. The GID matches the one listed for juan's primary group in /etc/passwd . 4. A new line for a group named juan is created in /etc/g shad o w: juan:!:: The line has the following characteristics: It begins with the group name juan. An exclamation mark (! ) appears in the password field of the /etc/g shad o w file, which locks the group. All other fields are blank. 5. A directory for user juan is created in the /ho me/ directory: ~]# l s -l d /ho me/juan drwx------. 4 juan juan 4096 Mar 3 18:23 /home/juan This directory is owned by user juan and group juan. It has read, write, and execute privileges only for the user juan. All other permissions are denied. 6. The files within the /etc/skel / directory (which contain default user settings) are copied into the new /ho me/juan/ directory: ~]# l s -l a /ho me/juan total 28 drwx------. 4 juan juan 4096 Mar 3 18:23 drwxr-xr-x. 5 root root 4096 Mar 3 18:23 -rw-r--r--. 1 juan juan 18 Jun 22 2010 -rw-r--r--. 1 juan juan 176 Jun 22 2010 -rw-r--r--. 1 juan juan 124 Jun 22 2010 drwxr-xr-x. 4 juan juan 4096 Nov 23 15:09 . .. .bash_logout .bash_profile .bashrc .mozilla At this point, a locked account called juan exists on the system. To activate it, the administrator must next assign a password to the account using the passwd command and, optionally, set password aging guidelines (see the Password Security section in the Red Hat Enterprise Linux 7 Security Guide for details). 3.3.2. Adding a New Group 26 Chapt er 3. Managing Users and G roups 3.3.2. Adding a New Group To add a new group to the system, type the following at a shell prompt as ro o t: g ro upad d [options] group_name …where options are command-line options as described in Table 3.3, “ Common groupadd command-line options” . T ab le 3.3. C o mmo n g ro u p ad d co mman d - lin e o p t io n s O p t io n D escrip t io n -f, --fo rce When used with -g gid and gid already exists, g ro upad d will choose another unique gid for the group. Group ID for the group, which must be unique and greater than 999. Override /etc/l o g i n. d efs defaults. Allow to create groups with duplicate. Use this encrypted password for the new group. Create a system group with a GID less than 1000. -g gid -K, --key key=value -o , --no n-uni q ue -p, --passwo rd password -r 3.3.3. Creat ing Group Direct ories System administrators usually like to create a group for each major project and assign people to the group when they need to access that project's files. With this traditional scheme, file management is difficult; when someone creates a file, it is associated with the primary group to which they belong. When a single person works on multiple projects, it becomes difficult to associate the right files with the right group. However, with the UPG scheme, groups are automatically assigned to files created within a directory with the setgid bit set. The setgid bit makes managing group projects that share a common directory very simple because any files a user creates within the directory are owned by the group that owns the directory. For example, a group of people need to work on files in the /o pt/mypro ject/ directory. Some people are trusted to modify the contents of this directory, but not everyone. 1. As ro o t, create the /o pt/mypro ject/ directory by typing the following at a shell prompt: mkd i r /o pt/mypro ject 2. Add the mypro ject group to the system: g ro upad d mypro ject 3. Associate the contents of the /o pt/mypro ject/ directory with the mypro ject group: cho wn ro o t: mypro ject /o pt/mypro ject 4. Allow users in the group to create files within the directory and set the setgid bit: chmo d 2775 /o pt/mypro ject At this point, all members of the mypro ject group can create and edit files in the /o pt/mypro ject/ directory without the administrator having to change file permissions every time users write new files. To verify that the permissions have been set correctly, run the following command: 27 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# l s -l d /o pt/mypro ject drwxrwsr-x. 3 root myproject 4096 Mar 3 18:31 /opt/myproject 5. Add users to the mypro ject group: usermo d -aG mypro ject username 3.4 . Addit ional Resources For more information on how to manage users and groups on Red Hat Enterprise Linux, see the resources listed below. Inst alled Document at ion For information about various utilities for managing users and groups, see the following manual pages: userad d (8) — The manual page for the userad d command documents how to use it to create new users. userd el (8) — The manual page for the userd el command documents how to use it to delete users. usermo d (8) — The manual page for the usermo d command documents how to use it to modify users. g ro upad d (8) — The manual page for the g ro upad d command documents how to use it to create new groups. g ro upd el (8) — The manual page for the g ro upd el command documents how to use it to delete groups. g ro upmo d (8) — The manual page for the g ro upmo d command documents how to use it to modify group membership. g passwd (1) — The manual page for the g passwd command documents how to manage the /etc/g ro up file. g rpck(8) — The manual page for the g rpck command documents how to use it to verify the integrity of the /etc/g ro up file. pwck(8) — The manual page for the pwck command documents how to use it to verify the integrity of the /etc/passwd and /etc/shad o w files. pwco nv(8) — The manual page for the pwco nv, pwunco nv, g rpco nv, and g rpunco nv commands documents how to convert shadowed information for passwords and groups. i d (1) — The manual page for the i d command documents how to display user and group ID s. For information about related configuration files, see: g ro up(5) — The manual page for the /etc/g ro up file documents how to use this file to define system groups. passwd (5) — The manual page for the /etc/passwd file documents how to use this file to define user information. 28 Chapt er 3. Managing Users and G roups shad o w(5) — The manual page for the /etc/shad o w file documents how to use this file to set passwords and account expiration information for the system. Online Document at ion Red Hat Enterprise Linux 7 Security Guide — The Security Guide for Red Hat Enterprise Linux 7 provides additional information how to ensure password security and secure the workstation by enabling password aging and user account locking. See Also Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. 29 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 4. Gaining Privileges System administrators, and in some cases users, need to perform certain tasks with administrative access. Accessing the system as the ro o t user is potentially dangerous and can lead to widespread damage to the system and data. This chapter covers ways to gain administrative privileges using setuid programs such as su and sud o . These programs allow specific users to perform tasks which would normally be available only to the ro o t user while maintaining a higher level of control and system security. See the Red Hat Enterprise Linux 7 Security Guide for more information on administrative controls, potential dangers and ways to prevent data loss resulting from improper use of privileged access. 4 .1. T he su Command When a user executes the su command, they are prompted for the ro o t password and, after authentication, are given a ro o t shell prompt. Once logged in using the su command, the user is the ro o t user and has absolute administrative access to the system. Note that this access is still subject to the restrictions imposed by SELinux, if it is enabled. In addition, once a user has become ro o t, it is possible for them to use the su command to change to any other user on the system without being prompted for a password. Because this program is so powerful, administrators within an organization may want to limit who has access to the command. One of the simplest ways to do this is to add users to the special administrative group called wheel. To do this, type the following command as ro o t: usermo d -G wheel username In the previous command, replace username with the user name you want to add to the wheel group. You can also use the U sers settings tool to modify group memberships, as follows. Note that you need administrator privileges to perform this procedure. 1. Press the Super key to enter the Activities Overview, type Users and then press Enter. The U sers settings tool appears. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. 2. To enable making changes, click the Unl o ck button, and enter a valid administrator password. 3. Click a user icon in the left column to display the user's properties in the right-hand pane. 4. Change the Acco u n t T yp e from Stand ard to Ad mi ni strato r. This will add the user to the wheel group. See Section 3.2, “ Managing Users in a Graphical Environment” for more information about the U sers tool. After you add the desired users to the wheel group, it is advisable to only allow these specific users to use the su command. To do this, edit the PAM configuration file for su, /etc/pam. d /su. Open this file in a text editor and uncomment the following line by removing the # character: #auth 30 required pam_wheel.so use_uid Chapt er 4 . G aining Privileges This change means that only members of the administrative group wheel can switch to another user using the su command. Note The ro o t user is part of the wheel group by default. 4 .2. T he sudo Command The sud o command offers another approach to giving users administrative access. When trusted users precede an administrative command with sud o , they are prompted for their own password. Then, when they have been authenticated and assuming that the command is permitted, the administrative command is executed as if they were the ro o t user. The basic format of the sud o command is as follows: sud o command In the above example, command would be replaced by a command normally reserved for the ro o t user, such as mo unt. The sud o command allows for a high degree of flexibility. For instance, only users listed in the /etc/sud o ers configuration file are allowed to use the sud o command and the command is executed in the user's shell, not a ro o t shell. This means the ro o t shell can be completely disabled as shown in the Red Hat Enterprise Linux 7 Security Guide. Each successful authentication using the sud o command is logged to the file /var/l o g /messag es and the command issued along with the issuer's user name is logged to the file /var/l o g /secure. If additional logging is required, use the pam_tty_aud i t module to enable TTY auditing for specified users by adding the following line to your /etc/pam. d /system-auth file: session required pam_tty_audit.so disable=pattern enable=pattern where pattern represents a comma-separated listing of users with an optional use of globs. For example, the following configuration will enable TTY auditing for the ro o t user and disable it for all other users: session required pam_tty_audit.so disable=* enable=root Another advantage of the sud o command is that an administrator can allow different users access to specific commands based on their needs. Administrators wanting to edit the sud o configuration file, /etc/sud o ers, should use the vi sud o command. To give someone full administrative privileges, type vi sud o and add a line similar to the following in the user privilege specification section: juan ALL=(ALL) ALL This example states that the user, juan, can use sud o from any host and execute any command. 31 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The example below illustrates the granularity possible when configuring sud o : %users localhost=/sbin/shutdown -h now This example states that any user can issue the command /sbi n/shutd o wn -h no w as long as it is issued from the console. The man page for sud o ers has a detailed listing of options for this file. Important There are several potential risks to keep in mind when using the sud o command. You can avoid them by editing the /etc/sud o ers configuration file using vi sud o as described above. Leaving the /etc/sud o ers file in its default state gives every user in the wheel group unlimited ro o t access. By default, sud o stores the sudoer's password for a five minute timeout period. Any subsequent uses of the command during this period will not prompt the user for a password. This could be exploited by an attacker if the user leaves his workstation unattended and unlocked while still being logged in. This behavior can be changed by adding the following line to the /etc/sud o ers file: Defaults timestamp_timeout=value where value is the desired timeout length in minutes. Setting the value to 0 causes sud o to require a password every time. If a sudoer's account is compromised, an attacker can use sud o to open a new shell with administrative privileges: sud o /bi n/bash Opening a new shell as ro o t in this or similar fashion gives the attacker administrative access for a theoretically unlimited amount of time, bypassing the timeout period specified in the /etc/sud o ers file and never requiring the attacker to input a password for sud o again until the newly opened session is closed. 4 .3. Addit ional Resources While programs allowing users to gain administrative privileges are a potential security risk, security itself is beyond the scope of this particular book. You should therefore refer to the resources listed below for more information regarding security and privileged access. Inst alled Document at ion su(1) — The manual page for su provides information regarding the options available with this command. sud o (8) — The manual page for sud o includes a detailed description of this command and lists options available for customizing its behavior. 32 Chapt er 4 . G aining Privileges pam(8) — The manual page describing the use of Pluggable Authentication Modules (PAM) for Linux. Online Document at ion Red Hat Enterprise Linux 7 Security Guide — The Security Guide for Red Hat Enterprise Linux 7 provides a more in-depth look at potential security issues pertaining to setuid programs as well as techniques used to alleviate these risks. See Also Chapter 3, Managing Users and Groups documents how to manage system users and groups in the graphical user interface and on the command line. 33 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Part II. Subscription and Support To receive updates to the software on a Red Hat Enterprise Linux system it must be subscribed to the Red Hat Content Delivery Network (CD N) and the appropriate repositories enabled. This part describes how to subscribe a system to the Red Hat Content D elivery Network. Red Hat provides support via the Customer Portal, and you can access this support directly from the command line using the R ed H at Su p p o rt T o o l. This part describes the use of this command-line tool. 34 Chapt er 5. Regist ering t he Syst em and Managing Subscript ions Chapter 5. Registering the System and Managing Subscriptions The subscription service provides a mechanism to handle Red Hat software inventory and allows you to install additional software or update already installed programs to newer versions using the yu m package manager. In Red Hat Enterprise Linux 7 the recommended way to register your system and attach subscriptions is to use Red Hat Subscription Management. Note It is also possible to register the system and attach subscriptions after installation during the firstboot process. For detailed information about firstboot see the Initial Setup and Firstboot chapter in the Installation Guide for Red Hat Enterprise Linux 7. Note that firstboot is only available on systems after a graphical installation or after a kickstart installation where a desktop and the X window system were installed and graphical login was enabled. 5.1. Regist ering t he Syst em and At t aching Subscript ions Complete the following steps to register your system and attach one or more subscriptions using Red Hat Subscription Management. Note that all subscri pti o n-manag er commands are supposed to be run as ro o t. 1. Run the following command to register your system. You will be prompted to enter your user name and password. Note that the user name and password are the same as your login credentials for Red Hat Customer Portal. subscri pti o n-manag er reg i ster 2. D etermine the pool ID of a subscription that you requires. To do so, type the following at a shell prompt to display a list of all subscriptions that are available for your system: subscri pti o n-manag er l i st --avai l abl e For each available subscription, this command displays its name, unique identifier, expiration date, and other details related to your subscription. The pool ID is listed on a line beginning with P o o l ID . 3. Attach the appropriate subscription to your system by entering a command as follows: subscri pti o n-manag er attach --po o l = pool_id Replace pool_id with the pool ID you determined in the previous step. To verify the list of subscriptions your system has currently attached, at any time, run: subscri pti o n-manag er l i st --co nsumed 35 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note The auto -attach option automatically attaches compatible subscriptions to the system so that you can register the system and attach subscriptions in one step by executing the following command: subscri pti o n-manag er reg i ster --auto -attach For more information on how to register your system using Red Hat Subscription Management and associate it with subscriptions, see the Red Hat Subscription Management collection of guides. 5.2. Managing Soft ware Reposit ories When a system is subscribed to the Red Hat Content D elivery Network, a repository file is created in the /etc/yum. repo s. d / directory. To verify that, use yu m to list all enabled repositories: yum repo l i st Red Hat Subscription Management also allows you to manually enable or disable software repositories provided by Red Hat. To list all available repositories, use the following command: subscri pti o n-manag er repo s --l i st The repository names depend on the specific version of Red Hat Enterprise Linux you are using and are in the following format: rhel-variant-rhscl-version-rpms rhel-variant-rhscl-version-debug-rpms rhel-variant-rhscl-version-source-rpms Where variant is the Red Hat Enterprise Linux system variant (server or wo rkstati o n), and version is the Red Hat Enterprise Linux system version (6 or 7), for example: rhel-server-rhscl-7-eus-rpms rhel-server-rhscl-7-eus-source-rpms rhel-server-rhscl-7-eus-debug-rpms To enable a repository, enter a command as follows: subscri pti o n-manag er repo s --enabl e repository Replace repository with a name of the repository to enable. Similarly, to disable a repository, use the following command: subscri pti o n-manag er repo s --d i sabl e repository Section 7.5, “ Configuring Yum and Yum Repositories” provides detailed information about managing software repositories using yu m. 36 Chapt er 5. Regist ering t he Syst em and Managing Subscript ions 5.3. Removing Subscript ions To remove a particular subscription, complete the following steps. 1. D etermine the serial number of the subscription you want to remove by listing information about already attached subscriptions: subscri pti o n-manag er l i st --co nsumed The serial number is the number listed as seri al . For instance, 74 4 9 9 3814 2510 16 831 in the example below: SKU: Contract: Account: Serial: Pool ID: Active: Quantity Used: Service Level: Service Type: Status Details: Subscription Type: Starts: Ends: System Type: ES0113909 01234567 1234567 744993814251016831 8a85f9894bba16dc014bccdd905a5e23 False 1 SELF-SUPPORT L1-L3 Standard 02/27/2015 02/27/2016 Virtual 2. Enter a command as follows to remove the selected subscription: subscri pti o n-manag er remo ve --seri al = serial_number Replace serial_number with the serial number you determined in the previous step. To remove all subscriptions attached to the system, run the following command: subscri pti o n-manag er remo ve --al l 5.4 . Addit ional Resources For more information on how to register your system using Red Hat Subscription Management and associate it with subscriptions, see the resources listed below. Inst alled Document at ion subscri pti o n-manag er(8) — the manual page for Red Hat Subscription Management provides a complete list of supported options and commands. Relat ed Books Red Hat Subscription Management collection of guides — These guides contain detailed information how to use Red Hat Subscription Management. Installation Guide — see the Initial Setup and Firstboot chapter for detailed information on how to 37 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide register during the firstboot process. See Also Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. Chapter 7, Yum provides information about using the yu m packages manager to install and update software. 38 Chapt er 6 . Accessing Support Using t he Red Hat Support T ool Chapter 6. Accessing Support Using the Red Hat Support Tool The R ed H at Su p p o rt T o o l, in the redhat-support-tool package, can function as both an interactive shell and as a single-execution program. It can be run over SSH or from any terminal. It enables, for example, searching the Red Hat Knowledgebase from the command line, copying solutions directly on the command line, opening and updating support cases, and sending files to Red Hat for analysis. 6.1. Inst alling t he Red Hat Support T ool The R ed H at Su p p o rt T o o l is installed by default on Red Hat Enterprise Linux. If required, to ensure that it is, enter the following command as ro o t: ~]# yum i nstal l red hat-suppo rt-to o l 6.2. Regist ering t he Red Hat Support T ool Using t he Command Line To register the Red Hat Support Tool to the customer portal using the command line, proceed as follows: 1. ~]# red hat-suppo rt-to o l co nfi g user username Where username is the user name of the Red Hat Customer Portal account. 2. ~]# red hat-suppo rt-to o l co nfi g passwo rd Please enter the password for username: 6.3. Using t he Red Hat Support T ool in Int eract ive Shell Mode To start the tool in interactive mode, enter the following command: ~]$ red hat-suppo rt-to o l Welcome to the Red Hat Support Tool. Command (? for help): The tool can be run as an unprivileged user, with a consequently reduced set of commands, or as ro o t. The commands can be listed by entering the ? character. The program or menu selection can be exited by entering the q or e character. You will be prompted for your Red Hat Customer Portal user name and password when you first search the Knowledgebase or support cases. Alternately, set the user name and password for your Red Hat Customer Portal account using interactive mode, and optionally save it to the configuration file. 6.4 . Configuring t he Red Hat Support T ool When in interactive mode, the configuration options can be listed by entering the command co nfi g --hel p: 39 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# red hat-suppo rt-to o l Welcome to the Red Hat Support Tool. Command (? for help): co nfi g --hel p Usage: config [options] config.optionUse the 'config' command to set or get configuration file values. Options: -h, --help show this help message and exit -g, --global Save configuration option in /etc/redhat-supporttool.conf. -u, --unset Unset configuration option. The configuration file options which can be set are: user : The Red Hat Customer Portal user. password : The Red Hat Customer Portal password. debug : CRITICAL, ERROR, WARNING, INFO, or DEBUG url : The support services URL. Default=https://api.access.redhat.com proxy_url : A proxy server URL. proxy_user: A proxy server user. proxy_password: A password for the proxy server user. ssl_ca : Path to certificate authorities to trust during communication. kern_debug_dir: Path to the directory where kernel debug symbols should be downloaded and cached. Default=/var/lib/redhat-supporttool/debugkernels Examples: - config user - config user my-rhn-username - config --unset user Pro ced u re 6 .1. R eg ist erin g t h e R ed H at Su p p o rt T o o l U sin g In t eract ive Mo d e To register the Red Hat Support Tool to the customer portal using interactive mode, proceed as follows: 1. Start the tool by entering the following command: ~]# red hat-suppo rt-to o l 2. Enter your Red Hat Customer Portal user name: Command (? for help): co nfi g user username To save your user name to the global configuration file, add the -g option. 3. Enter your Red Hat Customer Portal password: Command (? for help): co nfi g passwo rd Please enter the password for username: 6.4 .1. Saving Set t ings t o t he Configurat ion Files 40 Chapt er 6 . Accessing Support Using t he Red Hat Support T ool The R ed H at Su p p o rt T o o l, unless otherwise directed, stores values and options locally in the home directory of the current user, using the ~ /. red hat-suppo rt-to o l /red hat-suppo rtto o l . co nf configuration file. If required, it is recommended to save passwords to this file because it is only readable by that particular user. When the tool starts, it will read values from the global configuration file /etc/red hat-suppo rt-to o l . co nf and from the local configuration file. Locally stored values and options take precedence over globally stored settings. Warning It is recommended n o t to save passwords in the global /etc/red hat-suppo rtto o l . co nf configuration file because the password is just base6 4 encoded and can easily be decoded. In addition, the file is world readable. To save a value or option to the global configuration file, add the -g , --g l o bal option as follows: Command (? for help): co nfi g setting -g value Note In order to be able to save settings globally, using the -g , --g l o bal option, the R ed H at Su p p o rt T o o l must be run as ro o t because normal users do not have the permissions required to write to /etc/red hat-suppo rt-to o l . co nf. To remove a value or option from the local configuration file, add the -u, --unset option as follows: Command (? for help): co nfi g setting -u value This will clear, unset, the parameter from the tool and fall back to the equivalent setting in the global configuration file, if available. Note When running as an unprivileged user, values stored in the global configuration file cannot be removed using the -u, --unset option, but they can be cleared, unset, from the current running instance of the tool by using the -g , --g l o bal option simultaneously with the -u, --unset option. If running as ro o t, values and options can be removed from the global configuration file using -g , --g l o bal simultaneously with the -u, --unset option. 6.5. Opening and Updat ing Support Cases Using Int eract ive Mode Pro ced u re 6 .2. O p en in g a N ew Su p p o rt C ase U sin g In t eract ive Mo d e To open a new support case using interactive mode, proceed as follows: 1. Start the tool by entering the following command: ~]# red hat-suppo rt-to o l 41 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 2. Enter the o pencase command: Command (? for help): o pencase 3. Follow the on screen prompts to select a product and then a version. 4. Enter a summary of the case. 5. Enter a description of the case and press C trl +D on an empty line when complete. 6. Select a severity of the case. 7. Optionally chose to see if there is a solution to this problem before opening a support case. 8. Confirm you would still like to open the support case. Support case 0123456789 has successfully been opened 9. Optionally chose to attach an SOS report. 10. Optionally chose to attach a file. Pro ced u re 6 .3. Viewin g an d U p d at in g an Exist in g Su p p o rt C ase U sin g In t eract ive Mo d e To view and update an existing support case using interactive mode, proceed as follows: 1. Start the tool by entering the following command: ~]# red hat-suppo rt-to o l 2. Enter the g etcase command: Command (? for help): g etcase case-number Where case-number is the number of the case you want to view and update. 3. Follow the on screen prompts to view the case, modify or add comments, and get or add attachments. Pro ced u re 6 .4 . Mo d if yin g an Exist in g Su p p o rt C ase U sin g In t eract ive Mo d e To modify the attributes of an existing support case using interactive mode, proceed as follows: 1. Start the tool by entering the following command: ~]# red hat-suppo rt-to o l 2. Enter the mo d i fycase command: Command (? for help): mo d i fycase case-number Where case-number is the number of the case you want to view and update. 3. The modify selection list appears: 42 Chapt er 6 . Accessing Support Using t he Red Hat Support T ool Type the number of the attribute to modify or 'e' to return to the previous menu. 1 Modify Type 2 Modify Severity 3 Modify Status 4 Modify Alternative-ID 5 Modify Product 6 Modify Version End of options. Follow the on screen prompts to modify one or more of the options. 4. For example, to modify the status, enter 3: Selection: 3 1 Waiting on Customer 2 Waiting on Red Hat 3 Closed Please select a status (or 'q' to exit): 6.6. Viewing Support Cases on t he Command Line Viewing the contents of a case on the command line provides a quick and easy way to apply solutions from the command line. To view an existing support case on the command line, enter a command as follows: ~]# red hat-suppo rt-to o l g etcase case-number Where case-number is the number of the case you want to download. 6.7. Addit ional Resources The Red Hat Knowledgebase article Red Hat Support Tool has additional information, examples, and video tutorials. 43 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Part III. Installing and Managing Software All software on a Red Hat Enterprise Linux system is divided into RPM packages, which can be installed, upgraded, or removed. This part describes how to manage packages on Red Hat Enterprise Linux using Yu m. 44 Chapt er 7 . Yum Chapter 7. Yum Yu m is the Red Hat package manager that is able to query for information about available packages, fetch packages from repositories, install and uninstall them, and update an entire system to the latest available version. Yum performs automatic dependency resolution when updating, installing, or removing packages, and thus is able to automatically determine, fetch, and install all available dependent packages. Yum can be configured with new, additional repositories, or package sources, and also provides many plug-ins which enhance and extend its capabilities. Yum is able to perform many of the same tasks that R PM can; additionally, many of the command-line options are similar. Yum enables easy and simple package management on a single machine or on groups of them. The following sections assume your system was registered with Red Hat Subscription Management during installation as described in the Red Hat Enterprise Linux 7 Installation Guide. For additional information, see Using and Configuring Red Hat Subscription Manager. Important Yum provides secure package management by enabling GPG (Gnu Privacy Guard; also known as GnuPG) signature verification on GPG-signed packages to be turned on for all package repositories (i.e. package sources), or for individual repositories. When signature verification is enabled, yum will refuse to install any packages not GPG-signed with the correct key for that repository. This means that you can trust that the R PM packages you download and install on your system are from a trusted source, such as Red Hat, and were not modified during transfer. See Section 7.5, “ Configuring Yum and Yum Repositories” for details on enabling signature-checking with yum, or Section A.3.2, “ Checking Package Signatures” for information on working with and verifying GPG-signed R PM packages in general. Yum also enables you to easily set up your own repositories of R PM packages for download and installation on other machines. When possible, yum uses parallel download of multiple packages and metadata to speed up downloading. Learning yum is a worthwhile investment because it is often the fastest way to perform system administration tasks, and it provides capabilities beyond those provided by the Packag eK it graphical package management tools. Note You must have superuser privileges in order to use yum to install, update or remove packages on your system. All examples in this chapter assume that you have already obtained superuser privileges by using either the su or sud o command. 7.1. Checking For and Updat ing Packages Yum enables you to check if your system has any updates waiting to be applied. You can list packages that need to be updated and update them as a whole, or you can update a selected individual package. 7.1.1. Checking For Updat es 45 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To see which installed packages on your system have updates available, use the following command: yum check-upd ate Examp le 7.1. Examp le o u t p u t o f t h e yu m ch eck- u p d at e co mman d The output of yum check-upd ate can look as follows: ~]# yum check-upd ate Loaded plugins: langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 PackageKit.x86_64 0.5.8-2.el6 PackageKit-glib.x86_64 0.5.8-2.el6 PackageKit-yum.x86_64 0.5.8-2.el6 PackageKit-yum-plugin.x86_64 0.5.8-2.el6 glibc.x86_64 2.11.90-20.el6 glibc-common.x86_64 2.10.90-22 kernel.x86_64 2.6.31-14.el6 rpm.x86_64 4.7.1-5.el6 rpm-libs.x86_64 4.7.1-5.el6 rpm-python.x86_64 4.7.1-5.el6 yum.noarch 3.2.24-4.el6 rhel rhel rhel rhel rhel rhel rhel rhel rhel rhel rhel The packages in the above output are listed as having updates available. The first package in the list is Packag eK it , the graphical package manager. Each line in the example output consists of several rows, in case of Packag eK it : P ackag eKi t — the name of the package x86 _6 4 — the CPU architecture the package was built for 0 . 5. 8 — the version of the updated package to be installed rhel — the repository in which the updated package is located The output also shows that we can update the kernel (the kernel package), yum and RPM themselves (the yum and rpm packages), as well as their dependencies (such as the rpm-libs, and rpm-python packages), all using the yum command. 7.1.2. Updat ing Packages You can choose to update a single package, multiple packages, or all packages at once. If any dependencies of the package or packages you update have updates available themselves, then they are updated too. Updat ing a Single Package To update a single package, run the following command as ro o t: yum upd ate package_name 46 Chapt er 7 . Yum Examp le 7.2. U p d at in g t h e rp m p ackag e To update the rpm package, type: ~]# yum upd ate rpm Loaded plugins: langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 Setting up Update Process Resolving Dependencies --> Running transaction check ---> Package rpm.x86_64 0:4.11.1-3.el7 will be updated --> Processing Dependency: rpm = 4.11.1-3.el7 for package: rpm-libs4.11.1-3.el7.x86_64 --> Processing Dependency: rpm = 4.11.1-3.el7 for package: rpm-python4.11.1-3.el7.x86_64 --> Processing Dependency: rpm = 4.11.1-3.el7 for package: rpm-build4.11.1-3.el7.x86_64 ---> Package rpm.x86_64 0:4.11.2-2.el7 will be an update --> Running transaction check ... --> Finished Dependency Resolution Dependencies Resolved ====================================================================== ======= Package Arch Version Repository Size ====================================================================== ======= Updating: rpm x86_64 4.11.2-2.el7 rhel 1.1 M Updating for dependencies: rpm-build x86_64 4.11.2-2.el7 rhel 139 k rpm-build-libs x86_64 4.11.2-2.el7 rhel 98 k rpm-libs x86_64 4.11.2-2.el7 rhel 261 k rpm-python x86_64 4.11.2-2.el7 rhel 74 k Transaction Summary ====================================================================== ======= Upgrade 1 Package (+4 Dependent packages) Total size: 1.7 M Is this ok [y/d/N]: This output contains several items of interest: 47 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 1. Lo ad ed pl ug i ns: l ang packs, pro d uct-i d , subscri pti o n-manag er — Yum always informs you which yum plug-ins are installed and enabled. See Section 7.6, “ Yum Plug-ins” for general information on yum plug-ins, or Section 7.6.3, “ Working with Yum Plug-ins” for descriptions of specific plug-ins. 2. rpm. x86 _6 4 — you can download and install a new rpm package as well as its dependencies. Transaction check is performed for each of these packages. 3. Yum presents the update information and then prompts you for confirmation of the update; yum runs interactively by default. If you already know which transactions the yum command plans to perform, you can use the -y option to automatically answer yes to any questions that yum asks (in which case it runs non-interactively). However, you should always examine which changes yum plans to make to the system so that you can easily troubleshoot any problems that might arise. You can also choose to download the package without installing it. To do so, select the d option at the download prompt. This launches a background download of the selected package. If a transaction fails, you can view yum transaction history by using the yum hi sto ry command as described in Section 7.4, “ Working with Transaction History” . Important Yum always installs a new kernel regardless of whether you are using the yum upd ate or yum i nstal l command. When using R PM, on the other hand, it is important to use the rpm -i kernel command which installs a new kernel instead of rpm -u kernel which replaces the current kernel. See Section A.2.1, “ Installing and Upgrading Packages” for more information on installing and upgrading kernels with R PM. Similarly, it is possible to update a package group. Type as ro o t: yum g ro up upd ate group_name Here, replace group_name with a name of the package group you want to update. For more information on package groups, see Section 7.3, “ Working with Package Groups” . Yum also offers the upg rad e command that is equal to upd ate with enabled o bso l etes configuration option (see Section 7.5.1, “ Setting [main] Options” ). By default, o bso l etes is turned on in /etc/yum. co nf, which makes these two commands equivalent. Updat ing All Package s and T he ir De pe nde ncie s To update all packages and their dependencies, use the yum upd ate command without any arguments: yum upd ate Updat ing Se curit y-Re lat e d Package s 48 Chapt er 7 . Yum D iscovering which packages have security updates available and then updating those packages quickly and easily is important. Yum provides the plug-in for this purpose. The secu rit y plug-in extends the yum command with a set of highly-useful security-centric commands, subcommands and options. See Section 7.6.3, “ Working with Yum Plug-ins” for specific information. 7.1.3. Preserving Configurat ion File Changes You will inevitably make changes to the configuration files installed by packages as you use your Red Hat Enterprise Linux system. R PM, which yum uses to perform changes to the system, provides a mechanism for ensuring their integrity. See Section A.2.1, “ Installing and Upgrading Packages” for details on how to manage changes to configuration files across package upgrades. 7.2. Working wit h Packages Yum enables you to preform a complete set of operations with software packages, including searching for packages, viewing information about them, installing and removing. 7.2.1. Searching Packages You can search all RPM package names, descriptions and summaries by using the following command: yum search term… Replace term with a package name you want to search. Examp le 7.3. Search in g f o r p ackag es mat ch in g a sp ecif ic st rin g To list all packages that match “ meld” or “ kompare” , type: ~]$ yum search mel d ko mpare Loaded plugins: langpacks, langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 ============================ N/S matched: kompare ============================= ko mpare.x86_64 : Diff tool ... Name and summary matches mo stl y, use "search all" for everything. Warning: No matches found for: meld The yum search command is useful for searching for packages you do not know the name of, but for which you know a related term. Note that by default, yum search returns matches in package name and summary, which makes the search faster. Use the yum search al l command for a more exhaustive but slower search. Filt e ring t he Re sult s 49 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide All of yum's list commands allow you to filter the results by appending one or more glob expressions as arguments. Glob expressions are normal strings of characters which contain one or more of the wildcard characters * (which expands to match any character subset) and ? (which expands to match any single character). Be careful to escape the glob expressions when passing them as arguments to a yum command, otherwise the Bash shell will interpret these expressions as pathname expansions, and potentially pass all files in the current directory that match the global expressions to yum. To make sure the glob expressions are passed to yum as intended, use one of the following methods: escape the wildcard characters by preceding them with a backslash character double-quote or single-quote the entire glob expression. Examples in the following section demonstrate usage of both these methods. 7.2.2. List ing Packages To list information on all installed and available packages type the following at a shell prompt: yum l i st al l To list installed and available packages that match inserted glob expressions use the following command: yum l i st glob_expression… Examp le 7.4 . List in g AB R T - relat ed p ackag es Packages with various ABRT add-ons and plug-ins either begin with “ abrt-addon-” , or “ abrtplugin-” . To list these packages, type the following command at a shell prompt. Note how the wildcard characters are escaped with a backslash character: ~]$ yum l i st abrt-ad d o n\* abrt-pl ug i n\* Loaded plugins: langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 Installed Packages abrt-addon-ccpp.x86_64 1.0.7-5.el6 @ rhel abrt-addon-kerneloops.x86_64 1.0.7-5.el6 @ rhel abrt-addon-python.x86_64 1.0.7-5.el6 @ rhel abrt-plugin-bugzilla.x86_64 1.0.7-5.el6 @ rhel abrt-plugin-logger.x86_64 1.0.7-5.el6 @ rhel abrt-plugin-sosreport.x86_64 1.0.7-5.el6 @ rhel abrt-plugin-ticketuploader.x86_64 1.0.7-5.el6 @ rhel To list all packages installed on your system use the i nstal l ed keyword. The rightmost column in 50 Chapt er 7 . Yum the output lists the repository from which the package was retrieved. yum l i st i nstal l ed glob_expression… Examp le 7.5. List in g all in st alled versio n s o f t h e krb p ackag e The following example shows how to list all installed packages that begin with “ krb” followed by exactly one character and a hyphen. This is useful when you want to list all versions of certain component as these are distinguished by numbers. The entire glob expression is quoted to ensure proper processing. ~]$ yum l i st i nstal l ed "krb?-*" Loaded plugins: langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 Installed Packages krb5-libs.x86_64 1.8.1-3.el6 @ rhel krb5-workstation.x86_64 1.8.1-3.el6 @ rhel To list all packages in all enabled repositories that are available to install, use the command in the following form: yum l i st avai l abl e glob_expression… Examp le 7.6 . List in g availab le g st reamer p lu g - in s For instance, to list all available packages with names that contain “ gstreamer” and then “ plugin” , run the following command: ~]$ yum l i st avai l abl e g streamer\*pl ug i n\* Loaded plugins: langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 Available Packages gstreamer-plugins-bad-free.i686 0.10.17-4.el6 rhel gstreamer-plugins-base.i686 0.10.26-1.el6 rhel gstreamer-plugins-base-devel.i686 0.10.26-1.el6 rhel gstreamer-plugins-base-devel.x86_64 0.10.26-1.el6 rhel gstreamer-plugins-good.i686 0.10.18-1.el6 rhel List ing Re po sit o rie s 51 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To list the repository ID , name, and number of packages for each enabled repository on your system, use the following command: yum repo l i st To list more information about these repositories, add the -v option. With this option enabled, information including the file name, overall size, date of the last update, and base URL are displayed for each listed repository. As an alternative, you can use the repo i nfo command that produces the same output. yum repo l i st -v yum repo i nfo To list both enabled and disabled repositories use the following command. A status column is added to the output list to show which of the repositories are enabled. yum repo l i st al l By passing d i sabl ed as a first argument, you can reduce the command output to disabled repositories. For further specification you can pass the ID or name of repositories or related glob_expressions as arguments. Note that if there is an exact match between the repository ID or name and the inserted argument, this repository is listed even if it does not pass the enabled or disabled filter. 7.2.3. Displaying Package Informat ion To display information about one or more packages, use the following command (glob expressions are valid here as well): yum i nfo package_name… Replace package_name with the name of the package. Examp le 7.7. D isp layin g in f o rmat io n o n t h e ab rt p ackag e To display information about the abrt package, type: ~]$ yum i nfo abrt Loaded plugins: langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 Installed Packages Name : abrt Arch : x86_64 Version : 1.0.7 Release : 5.el6 Size : 578 k Repo : installed From repo : rhel Summary : Automatic bug detection and reporting tool URL : https://fedorahosted.org/abrt/ 52 Chapt er 7 . Yum License : Description: applications : by : : GPLv2+ abrt is a tool to help users to detect defects in and to create a bug report with all informations needed maintainer to fix it. It uses plugin system to extend its functionality. The yum i nfo package_name command is similar to the rpm -q --i nfo package_name command, but provides as additional information the ID of the yum repository the RPM package is found in (look for the Fro m repo : line in the output). Using yum db You can also query the yum database for alternative and useful information about a package by using the following command: yumd b i nfo package_name This command provides additional information about a package, including the checksum of the package (and the algorithm used to produce it, such as SHA-256), the command given on the command line that was invoked to install the package (if any), and the reason why the package is installed on the system (where user indicates it was installed by the user, and d ep means it was brought in as a dependency). Examp le 7.8. Q u eryin g yu md b f o r in f o rmat io n o n t h e yu m p ackag e To display additional information about the yum package, type: ~]$ yumd b i nfo yum Loaded plugins: langpacks, product-id, subscription-manager yum-3.2.27-4.el6.noarch checksum_data = 23d337ed51a9757bbfbdceb82c4eaca9808ff1009b51e9626d540f44fe95f771 checksum_type = sha256 from_repo = rhel from_repo_revision = 1298613159 from_repo_timestamp = 1298614288 installed_by = 4294967295 reason = user releasever = 6.1 For more information on the yumd b command, see the yu md b (8) manual page. 7.2.4 . Inst alling Packages To install a single package and all of its non-installed dependencies, enter a command in the following form as ro o t: yum i nstal l package_name 53 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide You can also install multiple packages simultaneously by appending their names as arguments. To do so, type as ro o t: yum i nstal l package_name package_name… If you are installing packages on a multilib system, such as an AMD 64 or Intel64 machine, you can specify the architecture of the package (as long as it is available in an enabled repository) by appending .arch to the package name: yum i nstal l package_name.arch Examp le 7.9 . In st allin g p ackag es o n mu lt ilib syst em To install the sqlite package for the i 6 86 architecture, type: ~]# yum i nstal l sq l i te. i 6 86 You can use glob expressions to quickly install multiple similarly named packages. Execute as ro o t: yum i nstal l glob_expression… Examp le 7.10. In st allin g all au d acio u s p lu g in s Global expressions are useful when you want to install several packages with similar names. To install all audacious plug-ins, use the command in the following form: ~]# yum i nstal l aud aci o us-pl ug i ns-\* In addition to package names and glob expressions, you can also provide file names to yum i nstal l . If you know the name of the binary you want to install, but not its package name, you can give yum i nstal l the path name. As ro o t, type: yum i nstal l /usr/sbi n/named Yum then searches through its package lists, finds the package which provides /usr/sbi n/named , if any, and prompts you as to whether you want to install it. As you can see in the above examples, the yum i nstal l command does not require strictly defined arguments. It can process various formats of package names and glob expressions, which makes installation easier for users. On the other hand, it takes some time until yu m parses the input correctly, especially if you specify a large number of packages. To optimize the package search, you can use the following commands to explicitly define how to parse the arguments: yum i nstal l -n name yum i nstal l -na name.architecture yum i nstal l -nevra name-epoch:version-release.architecture 54 Chapt er 7 . Yum With i nstal l -n, yu m interprets name as the exact name of the package. The i nstal l -na command tells yu m that the subsequent argument contains the package name and architecture divided by the dot character. With i nstal l -nevra, yu m will expect an argument in the form nameepoch:version-release.architecture. Similarly, you can use yum remo ve-n, yum remo ve-na, and yum remo ve-nevra when searching for packages to be removed. Note If you know you want to install the package that contains the named binary, but you do not know in which bi n or sbi n directory is the file installed, use the yum pro vi d es command with a glob expression: ~]# yum pro vi d es "*bi n/named " Loaded plugins: langpacks, product-id, subscription-manager Updating Red Hat repositories. INFO:rhsm-app.repolib:repos updated: 0 32:bind-9.7.0-4.P1.el6.x86_64 : The Berkeley Internet Name Domain (BIND) : DNS (Domain Name System) server Repo : rhel Matched from: Filename : /usr/sbin/named yum pro vi d es "*/file_name" is a common and useful trick to find the package(s) that contain file_name. Examp le 7.11. In st allat io n Pro cess The following example provides an overview of installation with use of yu m. To download and install the latest version of the httpd package, execute as ro o t: ~]# yum i nstal l httpd Loaded plugins: langpacks, product-id, subscription-manager Resolving Dependencies --> Running transaction check ---> Package httpd.x86_64 0:2.4.6-12.el7 will be updated ---> Package httpd.x86_64 0:2.4.6-13.el7 will be an update --> Processing Dependency: 2.4.6-13.el7 for package: httpd-2.4.613.el7.x86_64 --> Running transaction check ---> Package httpd-tools.x86_64 0:2.4.6-12.el7 will be updated ---> Package httpd-tools.x86_64 0:2.4.6-13.el7 will be an update --> Finished Dependency Resolution Dependencies Resolved After executing the above command, yu m loads the necessary plug-ins and runs the transaction check. In this case, httpd is already installed. Since the installed package is older than the latest currently available version, it will be updated. The same applies to the httpd-tools package that httpd depends on. Then, a transaction summary is displayed: 55 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ====================================================================== ========== Package Arch Version Repository Size ====================================================================== ========== Updating: httpd x86_64 2.4.6-13.el7 rhel-x86_64-server-7 1.2 M Updating for dependencies: httpd-tools x86_64 2.4.6-13.el7 rhel-x86_64-server-7 77 k Transaction Summary ====================================================================== ========== Upgrade 1 Package (+1 Dependent package) Total size: 1.2 M Is this ok [y/d/N]: In this step yu m prompts you to confirm the installation. Apart from y (yes) and N (no) options, you can choose d (download only) to download the packages but not to install them directly. If you choose y, the installation proceeds with the following messages until it is finished successfully. Downloading packages: Running transaction check Running transaction test Transaction test succeeded Running transaction Updating : httpd-tools-2.4.6-13.el7.x86_64 1/4 Updating : httpd-2.4.6-13.el7.x86_64 2/4 Cleanup : httpd-2.4.6-12.el7.x86_64 3/4 Cleanup : httpd-tools-2.4.6-12.el7.x86_64 4/4 Verifying : httpd-2.4.6-13.el7.x86_64 1/4 Verifying : httpd-tools-2.4.6-13.el7.x86_64 2/4 Verifying : httpd-tools-2.4.6-12.el7.x86_64 3/4 Verifying : httpd-2.4.6-12.el7.x86_64 4/4 Updated: httpd.x86_64 0:2.4.6-13.el7 Dependency Updated: httpd-tools.x86_64 0:2.4.6-13.el7 Complete! 56 Chapt er 7 . Yum To install a previously downloaded package from the local directory on your system, use the following command: yum l o cal i nstal l path Replace path with the path to the package you want to install. 7.2.5. Downloading Packages As shown in Example 7.11, “ Installation Process” , at a certain point of installation process you are prompted to confirm the installation with the following message: ... Total size: 1.2 M Is this ok [y/d/N]: ... With the d option, yum downloads the packages without installing them immediately. You can install these packages later offline with the yum l o cal i nstal l command or you can share them with a different device. D ownloaded packages are saved in one of the subdirectories of the cache directory, by default / var/cache/yum/$basearch/$rel easever/packag es/. The downloading proceeds in background mode so that you can use yu m for other operations in parallel. 7.2.6. Removing Packages Similarly to package installation, yum enables you to uninstall them. To uninstall a particular package, as well as any packages that depend on it, run the following command as ro o t: yum remo ve package_name… As when you install multiple packages, you can remove several at once by adding more package names to the command. Examp le 7.12. R emo vin g several p ackag es To remove totem, type the following at a shell prompt: ~]# yum remo ve to tem Similar to i nstal l , remo ve can take these arguments: package names glob expressions file lists package provides 57 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Warning Yum is not able to remove a package without also removing packages which depend on it. This type of operation, which can only be performed by R PM, is not advised, and can potentially leave your system in a non-functioning state or cause applications to not work correctly or crash. For further information, see Section A.2.2, “ Uninstalling Packages” in the R PM chapter. 7.3. Working wit h Package Groups A package group is a collection of packages that serve a common purpose, for instance System Tools or Sound and Video. Installing a package group pulls a set of dependent packages, saving time considerably. The yum g ro ups command is a top-level command that covers all the operations that act on package groups in yum. 7.3.1. List ing Package Groups The summary option is used to view the number of installed groups, available groups, available environment groups, and both installed and available language groups: yum g ro ups summary Examp le 7.13. Examp le o u t p u t o f yu m g ro u p s su mmary ~]$ yum g ro ups summary Loaded plugins: langpacks, product-id, subscription-manager Available Environment Groups: 12 Installed Groups: 10 Available Groups: 12 To list all package groups from yum repositories add the l i st option. You can filter the command output by group names. yum g ro up l i st glob_expression… Several optional arguments can be passed to this command, including hi d d en to list also groups not marked as user visible, and i d s to list group ID s. You can add l ang uag e, envi ro nment, i nstal l ed , or avai l abl e options to reduce the command output to a specific group type. To list mandatory and optional packages contained in a particular group, use the following command: yum g ro up i nfo glob_expression… Examp le 7.14 . Viewin g in f o rmat io n o n t h e Lib reO f f ice p ackag e g ro u p ~]$ yum g ro up i nfo Li breO ffi ce Loaded plugins: langpacks, product-id, subscription-manager 58 Chapt er 7 . Yum Group: LibreOffice Group-Id: libreoffice Description: LibreOffice Productivity Suite Mandatory Packages: =libreoffice-calc libreoffice-draw -libreoffice-emailmerge libreoffice-graphicfilter =libreoffice-impress =libreoffice-math =libreoffice-writer +libreoffice-xsltfilter Optional Packages: libreoffice-base libreoffice-pyuno As you can see in the above example, the packages included in the package group can have different states that are marked with the following symbols: " - " — Package is not installed and it will not be installed as a part of the package group. " + " — Package is not installed but it will be installed on the next yum upg rad e or yum g ro up upg rad e. " = " — Package is installed and it was installed as a part of the package group. no symbol — Package is installed but it was installed outside of the package group. This means that the yum g ro up remo ve will not remove these packages. These distinctions take place only when the g ro up_co mmand configuration parameter is set to o bjects, which is the default setting. Set this parameter to a different value if you do not want yum to track if a package was installed as a part of the group or separately, which will make " no symbol" packages equivalent to " =" packages. You can alter the above package states using the yum g ro up mark command. For example, yum g ro up mark packag es marks any given installed packages as members of a specified group. To avoid installation of new packages on group update, use yum g ro up mark bl ackl i st. See the yum(8) man page for more information on capabilities of yum g ro up mark. Note You can identify an environmental group with use of the @^ prefix and a package group can be marked with @. When using yum g ro up l i st, i nfo , i nstal l , or remo ve, pass @group_name to specify a package group, @^group_name to specify an environmental group, or group_name to include both. 7.3.2. Inst alling a Package Group Each package group has a name and a group ID (groupid). To list the names of all package groups, and their group ID s, which are displayed in parentheses, type: yum g ro up l i st i d s 59 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Examp le 7.15. Fin d in g n ame an d g ro u p id o f a p ackag e g ro u p To find the name or ID of a package group, for example a group related to the KD E desktop environment, type: ~]$ yum g ro up l i st i d s kd e\* Available environment groups: KDE Plasma Workspaces (kde-desktop-environment) Done Some groups are hidden by settings in the configured repositories. For example, on a server, make use of the hi d d en command option: ~]$ yum g ro up l i st hi d d en i d s kd e\* Loaded plugins: product-id, subscription-manager Available Groups: KDE (kde-desktop) Done You can install a package group by passing its full group name, without the groupid part, to the g ro up i nstal l command. As ro o t, type: yum g ro up i nstal l "group name" You can also install by groupid. As ro o t, execute the following command: yum g ro up i nstal l groupid You can pass the groupid or quoted group name to the i nstal l command if you prepend it with an @ symbol, which tells yum that you want to perform g ro up i nstal l . As ro o t, type: yum i nstal l @ group Replace group with the groupid or quoted group name. The same logic applies to environmental groups: yum i nstal l @ ^group Examp le 7.16 . Fo u r eq u ivalen t ways o f in st allin g t h e K D E D eskt o p g ro u p As mentioned before, you can use four alternative, but equivalent ways to install a package group. For KD E D esktop, the commands look as follows: ~]# ~]# ~]# ~]# yum yum yum yum g ro up i nstal l "KD E D eskto p" g ro up i nstal l kd e-d eskto p i nstal l @ "KD E D eskto p" i nstal l @ kd e-d eskto p 7.3.3. Removing a Package Group 60 Chapt er 7 . Yum You can remove a package group using syntax similar to the i nstal l syntax, with use of either name of the package group or its id. As ro o t, type: yum g ro up remo ve group_name yum g ro up remo ve groupid Also, you can pass the groupid or quoted name to the remo ve command if you prepend it with an @symbol, which tells yum that you want to perform g ro up remo ve. As ro o t, type: yum remo ve @ group Replace group with the groupid or quoted group name. Similarly, you can replace an environmental group: yum remo ve @ ^group Examp le 7.17. Fo u r eq u ivalen t ways o f remo vin g t h e KD E D eskto p g ro u p Similarly to install, you can use four alternative, but equivalent ways to remove a package group. For KD E D esktop, the commands look as follows: ~]# ~]# ~]# ~]# yum yum yum yum g ro up remo ve "KD E D eskto p" g ro up remo ve kd e-d eskto p remo ve @ "KD E D eskto p" remo ve @ kd e-d eskto p 7.4 . Working wit h T ransact ion Hist ory The yum hi sto ry command enables users to review information about a timeline of yum transactions, the dates and times they occurred, the number of packages affected, whether these transactions succeeded or were aborted, and if the RPM database was changed between transactions. Additionally, this command can be used to undo or redo certain transactions. All history data is stored in the history DB in the /var/l i b/yum/hi sto ry/ directory. 7.4 .1. List ing T ransact ions To display a list of the twenty most recent transactions, as ro o t, either run yum hi sto ry with no additional arguments, or type the following at a shell prompt: yum hi sto ry l i st To display all transactions, add the al l keyword: yum hi sto ry l i st al l To display only transactions in a given range, use the command in the following form: yum hi sto ry l i st start_id..end_id 61 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide You can also list only transactions regarding a particular package or packages. To do so, use the command with a package name or a glob expression: yum hi sto ry l i st glob_expression… Examp le 7.18. List in g t h e f ive o ld est t ran sact io n s In the output of yum hi sto ry l i st, the most recent transaction is displayed at the top of the list. To display information about the five oldest transactions stored in the history data base, type: ~]# yum hi sto ry l i st 1. . 5 Loaded plugins: langpacks, product-id, subscription-manager ID | Login user | Date and time | Action(s) | Altered -----------------------------------------------------------------------------5 | User | 2013-07-29 15:33 | Install | 1 4 | User | 2013-07-21 15:10 | Install | 1 3 | User | 2013-07-16 15:27 | I, U | 73 2 | System | 2013-07-16 15:19 | Update | 1 1 | System | 2013-07-16 14:38 | Install | 1106 history list All forms of the yum hi sto ry l i st command produce tabular output with each row consisting of the following columns: ID — an integer value that identifies a particular transaction. Lo g i n user — the name of the user whose login session was used to initiate a transaction. This information is typically presented in the Full Name form. For transactions that were not issued by a user (such as an automatic system update), System is used instead. D ate and ti me — the date and time when a transaction was issued. Acti o n(s) — a list of actions that were performed during a transaction as described in Table 7.1, “ Possible values of the Action(s) field” . Al tered — the number of packages that were affected by a transaction, possibly followed by additional information as described in Table 7.2, “ Possible values of the Altered field” . T ab le 7.1. Po ssib le valu es o f t h e Act io n ( s) f ield Act io n Ab b reviat i on D escrip t io n D o wng rad e D Erase Instal l E I At least one package has been downgraded to an older version. At least one package has been removed. At least one new package has been installed. 62 Chapt er 7 . Yum Act io n Ab b reviat i on D escrip t io n O bso l eti ng R ei nstal l Upd ate O R U At least one package has been marked as obsolete. At least one package has been reinstalled. At least one package has been updated to a newer version. T ab le 7.2. Po ssib le valu es o f t h e Alt ered f ield Symb o l D escrip t io n < Before the transaction finished, the rpmd b database was changed outside yum. After the transaction finished, the rpmd b database was changed outside yum. The transaction failed to finish. The transaction finished successfully, but yum returned a non-zero exit code. The transaction finished successfully, but an error or a warning was displayed. The transaction finished successfully, but problems already existed in the rpmd b database. The transaction finished successfully, but the --ski p-bro ken command-line option was used and certain packages were skipped. > * # E P s To synchronize the rpmd b or yumd b database contents for any installed package with the currently used rpmd b or yumd b database, type the following: yum hi sto ry sync To display some overall statistics about the currently used history database use the following command: yum hi sto ry stats Examp le 7.19 . Examp le o u t p u t o f yu m h ist o ry st at s ~]# yum hi sto ry stats Loaded plugins: langpacks, product-id, subscription-manager File : //var/lib/yum/history/history-2012-08-15.sqlite Size : 2,766,848 Transactions: 41 Begin time : Wed Aug 15 16:18:25 2012 End time : Wed Feb 27 14:52:30 2013 Counts : NEVRAC : 2,204 NEVRA : 2,204 NA : 1,759 NEVR : 2,204 rpm DB : 2,204 yum DB : 2,204 history stats Yum also enables you to display a summary of all past transactions. To do so, run the command in the following form as ro o t: 63 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide yum hi sto ry summary To display only transactions in a given range, type: yum hi sto ry summary start_id..end_id Similarly to the yum hi sto ry l i st command, you can also display a summary of transactions regarding a certain package or packages by supplying a package name or a glob expression: yum hi sto ry summary glob_expression… Examp le 7.20. Su mmary o f t h e f ive lat est t ran sact io n s ~]# yum hi sto ry summary 1. . 5 Loaded plugins: langpacks, product-id, subscription-manager Login user | Time | Action(s) | Altered -----------------------------------------------------------------------------Jaromir ... | Last day | Install | 1 Jaromir ... | Last week | Install | 1 Jaromir ... | Last 2 weeks | I, U | 73 System | Last 2 weeks | I, U | 1107 history summary All forms of the yum hi sto ry summary command produce simplified tabular output similar to the output of yum hi sto ry l i st. As shown above, both yum hi sto ry l i st and yum hi sto ry summary are oriented towards transactions, and although they allow you to display only transactions related to a given package or packages, they lack important details, such as package versions. To list transactions from the perspective of a package, run the following command as ro o t: yum hi sto ry packag e-l i st glob_expression… Examp le 7.21. T racin g t h e h ist o ry o f a p ackag e For example, to trace the history of subscription-manager and related packages, type the following at a shell prompt: ~]# yum hi sto ry packag e-l i st subscri pti o n-manag er\* Loaded plugins: langpacks, product-id, subscription-manager ID | Action(s) | Package -----------------------------------------------------------------------------3 | Updated | subscription-manager-1.10.11-1.el6.x86_64 3 | Update | 1.10.17-1.el6_1.x86_64 64 Chapt er 7 . Yum 3 | Updated 1.el6.x86_64 3 | Update 1.el6_1.x86_64 3 | Updated 3 | Update 1.el6_1.x86_64 1 | Install 1 | Install 1.el6.x86_64 1 | Install history package-list | subscription-manager-firstboot-1.10.11| 1.10.17- | subscription-manager-gui-1.10.11-1.el6.x86_64 | 1.10.17| subscription-manager-1.10.11-1.el6.x86_64 | subscription-manager-firstboot-1.10.11| subscription-manager-gui-1.10.11-1.el6.x86_64 In this example, three packages were installed during the initial system installation: subscriptionmanager, subscription-manager-firstboot, and subscription-manager-gui. In the third transaction, all these packages were updated from version 1.10.11 to version 1.10.17. 7.4 .2. Examining T ransact ions To display the summary of a single transaction, as ro o t, use the yum hi sto ry summary command in the following form: yum hi sto ry summary id Here, id stands for the ID of the transaction. To examine a particular transaction or transactions in more detail, run the following command as ro o t: yum hi sto ry i nfo id… The id argument is optional and when you omit it, yum automatically uses the last transaction. Note that when specifying more than one transaction, you can also use a range: yum hi sto ry i nfo start_id..end_id Examp le 7.22. Examp le o u t p u t o f yu m h ist o ry in f o The following is sample output for two transactions, each installing one new package: ~]# yum hi sto ry i nfo 4 . . 5 Loaded plugins: langpacks, product-id, subscription-manager Transaction ID : 4..5 Begin time : Thu Jul 21 15:10:46 2011 Begin rpmdb : 1107:0c67c32219c199f92ed8da7572b4c6df64eacd3a End time : 15:33:15 2011 (22 minutes) End rpmdb : 1109:1171025bd9b6b5f8db30d063598f590f1c1f3242 User : Jaromir Hradilek Return-Code : Success Command Line : install screen Command Line : install yum-plugin-aliases Transaction performed with: 65 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Installed rpm-4.8.0-16.el6.x86_64 Installed yum-3.2.29-17.el6.noarch Installed yum-metadata-parser-1.1.2-16.el6.x86_64 Packages Altered: Install screen-4.0.3-16.el6.x86_64 Install yum-plugin-aliases-1.1.30-6.el6.noarch history info You can also view additional information, such as what configuration options were used at the time of the transaction, or from what repository and why were certain packages installed. To determine what additional information is available for a certain transaction, type the following at a shell prompt as ro o t: yum hi sto ry ad d o n-i nfo id Similarly to yum hi sto ry i nfo , when no id is provided, yum automatically uses the latest transaction. Another way to refer to the latest transaction is to use the l ast keyword: yum hi sto ry ad d o n-i nfo l ast Examp le 7.23. Examp le o u t p u t o f yum hi sto ry ad d o n-i nfo For the fourth transaction in the history, the yum hi sto ry ad d o n-i nfo command provides the following output: ~]# yum hi sto ry ad d o n-i nfo 4 Loaded plugins: langpacks, product-id, subscription-manager Transaction ID: 4 Available additional history information: config-main config-repos saved_tx history addon-info In the output of the yum hi sto ry ad d o n-i nfo command, three types of information are available: co nfi g -mai n — global yum options that were in use during the transaction. See Section 7.5.1, “ Setting [main] Options” for information on how to change global options. co nfi g -repo s — options for individual yum repositories. See Section 7.5.2, “ Setting [repository] Options” for information on how to change options for individual repositories. saved _tx — the data that can be used by the yum l o ad -transacti o n command in order to repeat the transaction on another machine (see below). To display a selected type of additional information, run the following command as ro o t: yum hi sto ry ad d o n-i nfo id information 7.4 .3. Revert ing and Repeat ing T ransact ions 66 Chapt er 7 . Yum Apart from reviewing the transaction history, the yum hi sto ry command provides means to revert or repeat a selected transaction. To revert a transaction, type the following at a shell prompt as ro o t: yum hi sto ry und o id To repeat a particular transaction, as ro o t, run the following command: yum hi sto ry red o id Both commands also accept the l ast keyword to undo or repeat the latest transaction. Note that both yum hi sto ry und o and yum hi sto ry red o commands only revert or repeat the steps that were performed during a transaction. If the transaction installed a new package, the yum hi sto ry und o command will uninstall it, and if the transaction uninstalled a package the command will again install it. This command also attempts to downgrade all updated packages to their previous version, if these older packages are still available. When managing several identical systems, yum also enables you to perform a transaction on one of them, store the transaction details in a file, and after a period of testing, repeat the same transaction on the remaining systems as well. To store the transaction details to a file, type the following at a shell prompt as ro o t: yum -q hi sto ry ad d o n-i nfo id saved _tx > fi l e_name Once you copy this file to the target system, you can repeat the transaction by using the following command as ro o t: yum l o ad -transacti o n file_name You can configure l o ad -transacti o n to ignore missing packages or rpmdb version. For more information on these configuration options see the yum. co nf(5) man page. 7.4 .4 . St art ing New T ransact ion Hist ory Yum stores the transaction history in a single SQLite database file. To start new transaction history, run the following command as ro o t: yum hi sto ry new This will create a new, empty database file in the /var/l i b/yum/hi sto ry/ directory. The old transaction history will be kept, but will not be accessible as long as a newer database file is present in the directory. 7.5. Configuring Yum and Yum Reposit ories The configuration information for yum and related utilities is located at /etc/yum. co nf. This file contains one mandatory [mai n] section, which enables you to set yum options that have global effect, and can also contain one or more [repository] sections, which allow you to set repositoryspecific options. However, it is recommended to define individual repositories in new or existing . repo files in the /etc/yum. repo s. d /directory. The values you define in the [mai n] section of the /etc/yum. co nf file can override values set in individual [repository] sections. This section shows you how to: 67 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide set global yum options by editing the [mai n] section of the /etc/yum. co nf configuration file; set options for individual repositories by editing the [repository] sections in /etc/yum. co nf and . repo files in the /etc/yum. repo s. d / directory; use yum variables in /etc/yum. co nf and files in the /etc/yum. repo s. d / directory so that dynamic version and architecture values are handled correctly; add, enable, and disable yum repositories on the command line; and set up your own custom yum repository. 7.5.1. Set t ing [main] Opt ions The /etc/yum. co nf configuration file contains exactly one [mai n] section, and while some of the key-value pairs in this section affect how yum operates, others affect how yum treats repositories. You can add many additional options under the [mai n] section heading in /etc/yum. co nf. A sample /etc/yum. co nf configuration file can look like this: [main] cachedir=/var/cache/yum/$basearch/$releasever keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=3 [comments abridged] # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d The following are the most commonly used options in the [mai n] section: assumeyes= value The assumeyes option determines whether or not yum prompts for confirmation of critical actions. Replace value with one of: 0 (default) — yum prompts for confirmation of critical actions it performs. 1 — D o not prompt for confirmation of critical yum actions. If assumeyes= 1 is set, yum behaves in the same way as the command-line options -y and --assumeyes. cached i r= directory Use this option to set the directory where yum stores its cache and database files. Replace directory with an absolute path to the directory. By default, yum's cache directory is /var/cache/yum/$basearch/$rel easever. See Section 7.5.3, “ Using Yum Variables” for descriptions of the $basearch and $rel easever yum variables. d ebug l evel = value 68 Chapt er 7 . Yum This option specifies the detail of debugging output produced by yum. Here, value is an integer between 1 and 10 . Setting a higher d ebug l evel value causes yum to display more detailed debugging output. d ebug l evel = 2 is the default, while d ebug l evel = 0 disables debugging output. exactarch= value With this option, you can set yum to consider the exact architecture when updating already installed packages. Replace value with: 0 — D o not take into account the exact architecture when updating packages. 1 (default) — Consider the exact architecture when updating packages. With this setting, yum does not install a package for 32-bit architecture to update a package already installed on the system with 64-bit architecture. excl ud e= package_name [ more_package_names] The excl ud e option enables you to exclude packages by keyword during installation or system update. Listing multiple packages for exclusion can be accomplished by quoting a space-delimited list of packages. Shell glob expressions using wildcards (for example, * and ?) are allowed. g pg check= value Use the g pg check option to specify if yum should perform a GPG signature check on packages. Replace value with: 0 — D isable GPG signature-checking on packages in all repositories, including local package installation. 1 (default) — Enable GPG signature-checking on all packages in all repositories, including local package installation. With g pg check enabled, all packages' signatures are checked. If this option is set in the [mai n] section of the /etc/yum. co nf file, it sets the GPGchecking rule for all repositories. However, you can also set g pg check= value for individual repositories instead; that is, you can enable GPG-checking on one repository while disabling it on another. Setting g pg check= value for an individual repository in its corresponding . repo file overrides the default if it is present in /etc/yum. co nf. For more information on GPG signature-checking, see Section A.3.2, “ Checking Package Signatures” . g ro up_co mmand = value Use the g ro up_co mmand option to specify how the yum g ro up i nstal l , yum g ro up upg rad e, and yum g ro up remo ve commands handle a package group. Replace value with on of: si mpl e — Install all members of a package group. Upgrade only previously installed packages, but do not install packages that have been added to the group in the meantime. co mpat — Similar to si mpl e but yum upg rad e also installs packages that were added to the group since the previous upgrade. o bjects — (default.) With this option, yum keeps track of the previously installed groups and distinguishes between packages installed as a part of the group and packages installed separately. See Example 7.14, “ Viewing information on the LibreOffice package group” 69 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide g ro up_packag e_types= package_type [ more_package_types] Here you can specify which type of packages (optional, default or mandatory) is installed when the yum g ro up i nstal l command is called. The default and mandatory package types are chosen by default. hi sto ry_reco rd = value With this option, you can set yum to record transaction history. Replace value with one of: 0 — yum should not record history entries for transactions. 1 (default) — yum should record history entries for transactions. This operation takes certain amount of disk space, and some extra time in the transactions, but it provides a lot of information about past operations, which can be displayed with the yum hi sto ry command. hi sto ry_reco rd = 1 is the default. For more information on the yum hi sto ry command, see Section 7.4, “ Working with Transaction History” . Note Yum uses history records to detect modifications to the rpmd b data base that have been done outside of yum. In such case, yum displays a warning and automatically searches for possible problems caused by altering rpmd b. With hi sto ry_reco rd turned off, yum is not able to detect these changes and no automatic checks are performed. i nstal l o nl ypkg s= space separated list of packages Here you can provide a space-separated list of packages which yum can install, but will never update. See the yum. co nf(5) manual page for the list of packages which are installonly by default. If you add the i nstal l o nl ypkg s directive to /etc/yum. co nf, you should ensure that you list all of the packages that should be install-only, including any of those listed under the i nstal l o nl ypkg s section of yum. co nf(5). In particular, kernel packages should always be listed in i nstal l o nl ypkg s (as they are by default), and i nstal l o nl y_l i mi t should always be set to a value greater than 2 so that a backup kernel is always available in case the default one fails to boot. i nstal l o nl y_l i mi t= value This option sets how many packages listed in the i nstal l o nl ypkg s directive can be installed at the same time. Replace value with an integer representing the maximum number of versions that can be installed simultaneously for any single package listed in i nstal l o nl ypkg s. The defaults for the i nstal l o nl ypkg s directive include several different kernel packages, so be aware that changing the value of i nstal l o nl y_l i mi t also affects the maximum number of installed versions of any single kernel package. The default value listed in /etc/yum. co nf is i nstal l o nl y_l i mi t= 3, and it is not recommended to decrease this value, particularly below 2. keepcache= value The keepcache option determines whether yum keeps the cache of headers and packages after successful installation. Here, value is one of: 70 Chapt er 7 . Yum after successful installation. Here, value is one of: 0 (default) — D o not retain the cache of headers and packages after a successful installation. 1 — Retain the cache after a successful installation. l o g fi l e= file_name To specify the location for logging output, replace file_name with an absolute path to the file in which yum should write its logging output. By default, yum logs to /var/l o g /yum. l o g . max_co nnencti o ns= number Here value stands for the maximum number of simultaneous connections, default is 5. mul ti l i b_po l i cy= value The mul ti l i b_po l i cy option sets the installation behavior if several architecture versions are available for package install. Here, value stands for: best — install the best-choice architecture for this system. For example, setting mul ti l i b_po l i cy= best on an AMD 64 system causes yum to install the 64-bit versions of all packages. al l — always install every possible architecture for every package. For example, with mul ti l i b_po l i cy set to al l on an AMD 64 system, yum would install both the i686 and AMD 64 versions of a package, if both were available. o bso l etes= value The o bso l etes option enables the obsoletes process logic during updates.When one package declares in its spec file that it obsoletes another package, the latter package is replaced by the former package when the former package is installed. Obsoletes are declared, for example, when a package is renamed. Replace value with one of: 0 — D isable yum's obsoletes processing logic when performing updates. 1 (default) — Enable yum's obsoletes processing logic when performing updates. pl ug i ns= value This is a global switch to enable or disable yum plug-ins, value is one of: 0 — D isable all yum plug-ins globally. Important D isabling all plug-ins is not advised because certain plug-ins provide important yum services. In particular, p ro d u ct - id and su b scrip t io n - man ag er plug-ins provide support for the certificate-based C o ntent D el i very Netwo rk (CD N). D isabling plug-ins globally is provided as a convenience option, and is generally only recommended when diagnosing a potential problem with yum. 1 (default) — Enable all yum plug-ins globally. With pl ug i ns= 1, you can still disable a specific yum plug-in by setting enabl ed = 0 in that plug-in's configuration file. 71 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide For more information about various yum plug-ins, see Section 7.6, “ Yum Plug-ins” . For further information on controlling plug-ins, see Section 7.6.1, “ Enabling, Configuring, and D isabling Yum Plug-ins” . repo sd i r= directory Here, directory is an absolute path to the directory where . repo files are located. All . repo files contain repository information (similar to the [repository] sections of /etc/yum. co nf). Yum collects all repository information from . repo files and the [repository] section of the /etc/yum. co nf file to create a master list of repositories to use for transactions. If repo sd i r is not set, yum uses the default directory /etc/yum. repo s. d /. retri es= value This option sets the number of times yum should attempt to retrieve a file before returning an error. value is an integer 0 or greater. Setting value to 0 makes yum retry forever. The default value is 10 . For a complete list of available [mai n] options, see the [mai n] O P T IO NS section of the yu m.co n f (5) manual page. 7.5.2. Set t ing [reposit ory] Opt ions The [repository] sections, where repository is a unique repository ID such as my_perso nal _repo (spaces are not permitted), allow you to define individual yum repositories. The following is a bare minimum example of the form a [repository] section takes: [repository] name=repository_name baseurl=repository_url Every [repository] section must contain the following directives: name= repository_name Here, repository_name is a human-readable string describing the repository. baseurl = repository_url Replace repository_url with a URL to the directory where the repodata directory of a repository is located: If the repository is available over HTTP, use: http: //path/to /repo If the repository is available over FTP, use: ftp: //path/to /repo If the repository is local to the machine, use: fi l e: ///path/to /l o cal /repo If a specific online repository requires basic HTTP authentication, you can specify your user name and password by prepending it to the URL as username: password@ link. For example, if a repository on http://www.example.com/repo/ requires a username of “ user” and a password of “ password” , then the baseurl link could be specified as http: //user: passwo rd @ www. exampl e. co m/repo /. Usually this URL is an HTTP link, such as: 72 Chapt er 7 . Yum baseurl=http://path/to/repo/releases/$releasever/server/$basearch/ os/ Note that yum always expands the $rel easever, $arch, and $basearch variables in URLs. For more information about yum variables, see Section 7.5.3, “ Using Yum Variables” . Other useful [repository] directive are: enabl ed = value This is a simple way to tell yum to use or ignore a particular repository, value is one of: 0 — D o not include this repository as a package source when performing updates and installs. This is an easy way of quickly turning repositories on and off, which is useful when you desire a single package from a repository that you do not want to enable for updates or installs. 1 — Include this repository as a package source. Turning repositories on and off can also be performed by passing either the -enabl erepo = repo_name or --d i sabl erepo = repo_name option to yum, or through the Ad d /R emo ve So ftware window of the Packag eK it utility. async= value Controls parallel downloading of repository packages. Here, value is one of: auto (default) — parallel downloading is used if possible, which means that yu m automatically disables it for repositories created by plug-ins to avoid failures. o n — parallel downloading is enabled for the repository. o ff — parallel downloading is disabled for the repository. Many more [repository] options exist, part of them have the same form and function as certain [main] options. For a complete list, see the [repo si to ry] O P T IO NS section of the yu m.co n f (5) manual page. Examp le 7.24 . A samp le /et c/yu m.rep o s.d /red h at .rep o f ile The following is a sample /etc/yum. repo s. d /red hat. repo file: # # Red Hat Repositories # Managed by (rhsm) subscription-manager # [red-hat-enterprise-linux-scalable-file-system-for-rhel-6-entitlementrpms] name = Red Hat Enterprise Linux Scalable File System (for RHEL 6 Entitlement) (RPMs) baseurl = https://cdn.redhat.com/content/dist/rhel/entitlement6/releases/$releasever/$basearch/scalablefilesystem/os enabled = 1 gpgcheck = 1 gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release sslverify = 1 73 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide sslcacert = /etc/rhsm/ca/redhat-uep.pem sslclientkey = /etc/pki/entitlement/key.pem sslclientcert = /etc/pki/entitlement/11300387955690106.pem [red-hat-enterprise-linux-scalable-file-system-for-rhel-6-entitlementsource-rpms] name = Red Hat Enterprise Linux Scalable File System (for RHEL 6 Entitlement) (Source RPMs) baseurl = https://cdn.redhat.com/content/dist/rhel/entitlement6/releases/$releasever/$basearch/scalablefilesystem/source/SRPMS enabled = 0 gpgcheck = 1 gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release sslverify = 1 sslcacert = /etc/rhsm/ca/redhat-uep.pem sslclientkey = /etc/pki/entitlement/key.pem sslclientcert = /etc/pki/entitlement/11300387955690106.pem [red-hat-enterprise-linux-scalable-file-system-for-rhel-6-entitlementdebug-rpms] name = Red Hat Enterprise Linux Scalable File System (for RHEL 6 Entitlement) (Debug RPMs) baseurl = https://cdn.redhat.com/content/dist/rhel/entitlement6/releases/$releasever/$basearch/scalablefilesystem/debug enabled = 0 gpgcheck = 1 gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release sslverify = 1 sslcacert = /etc/rhsm/ca/redhat-uep.pem sslclientkey = /etc/pki/entitlement/key.pem sslclientcert = /etc/pki/entitlement/11300387955690106.pem 7.5.3. Using Yum Variables You can use and reference the following built-in variables in yum commands and in all yum configuration files (that is, /etc/yum. co nf and all . repo files in the /etc/yum. repo s. d / directory): $rel easever You can use this variable to reference the release version of Red Hat Enterprise Linux. Yum obtains the value of $rel easever from the d i stro verpkg = value line in the /etc/yum. co nf configuration file. If there is no such line in /etc/yum. co nf, then yum infers the correct value by deriving the version number from the red hat-rel ease file. $arch You can use this variable to refer to the system's CPU architecture as returned when calling Python's o s. uname() function. Valid values for $arch include: i 586 , i 6 86 and x86 _6 4 . $basearch You can use $basearch to reference the base architecture of the system. For example, i686 and i586 machines both have a base architecture of i 386 , and AMD 64 and Intel64 machines have a base architecture of x86 _6 4 . 74 Chapt er 7 . Yum $Y UM0 -9 These ten variables are each replaced with the value of any shell environment variables with the same name. If one of these variables is referenced (in /etc/yum. co nf for example) and a shell environment variable with the same name does not exist, then the configuration file variable is not replaced. To define a custom variable or to override the value of an existing one, create a file with the same name as the variable (without the “ $” sign) in the /etc/yum/vars/ directory, and add the desired value on its first line. For example, repository descriptions often include the operating system name. To define a new variable called $o sname, create a new file with “ Red Hat Enterprise Linux” on the first line and save it as /etc/yum/vars/o sname: ~]# echo "R ed Hat Enterpri se Li nux 7" > /etc/yum/vars/o sname Instead of “ Red Hat Enterprise Linux 7” , you can now use the following in the . repo files: name=$osname $releasever 7.5.4 . Viewing t he Current Configurat ion To display the current values of global yum options (that is, the options specified in the [mai n] section of the /etc/yum. co nf file), execute the yum-co nfi g -manag er command with no command-line options: yum-co nfi g -manag er To list the content of a different configuration section or sections, use the command in the following form: yum-co nfi g -manag er section… You can also use a glob expression to display the configuration of all matching sections: yum-co nfi g -manag er glob_expression… Examp le 7.25. Viewin g co n f ig u rat io n o f t h e main sect io n To list all configuration options and their corresponding values for the main section, type the following at a shell prompt: ~]$ yum-co nfi g -manag er mai n \* Loaded plugins: langpacks, product-id, subscription-manager ================================== main =================================== [main] alwaysprompt = True assumeyes = False bandwith = 0 75 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide bugtracker_url = https://bugzilla.redhat.com/enter_bug.cgi? product=Red%20Hat%20Enterprise%20Linux%206& component=yum cache = 0 [output truncated] 7.5.5. Adding, Enabling, and Disabling a Yum Reposit ory Section 7.5.2, “ Setting [repository] Options” describes various options you can use to define a yum repository. This section explains how to add, enable, and disable a repository by using the yumco nfi g -manag er command. Important When the system is registered with Red Hat Subscription Management to the certificate-based C o ntent D el i very Netwo rk (CD N), the R ed H at Su b scrip t io n Man ag er tools are used to manage repositories in the /etc/yum. repo s. d /red hat. repo file. Adding a Yum Re po sit o ry To define a new repository, you can either add a [repository] section to the /etc/yum. co nf file, or to a . repo file in the /etc/yum. repo s. d / directory. All files with the . repo file extension in this directory are read by yum, and it is recommended to define your repositories here instead of in /etc/yum. co nf. Warning Obtaining and installing software packages from unverified or untrusted software sources other than Red Hat's certificate-based C o ntent D el i very Netwo rk (CD N) constitutes a potential security risk, and could lead to security, stability, compatibility, and maintainability issues. Yum repositories commonly provide their own . repo file. To add such a repository to your system and enable it, run the following command as ro o t: yum-co nfi g -manag er --ad d -repo repository_url …where repository_url is a link to the . repo file. Examp le 7.26 . Ad d in g examp le.rep o To add a repository located at http://www.example.com/example.repo, type the following at a shell prompt: ~]# yum-co nfi g -manag er --ad d -repo http: //www. exampl e. co m/exampl e. repo Loaded plugins: langpacks, product-id, subscription-manager adding repo from: http://www.example.com/example.repo grabbing file http://www.example.com/example.repo to 76 Chapt er 7 . Yum /etc/yum.repos.d/example.repo example.repo 00:00 repo saved to /etc/yum.repos.d/example.repo | 413 B Enabling a Yum Re po sit o ry To enable a particular repository or repositories, type the following at a shell prompt as ro o t: yum-co nfi g -manag er --enabl e repository… …where repository is the unique repository ID (use yum repo l i st al l to list available repository ID s). Alternatively, you can use a glob expression to enable all matching repositories: yum-co nfi g -manag er --enabl e glob_expression… Examp le 7.27. En ab lin g rep o sit o ries d ef in ed in cu st o m sect io n s o f /et c/yu m.co n f . To enable repositories defined in the [exampl e], [exampl e-d ebug i nfo ], and [exampl eso urce]sections, type: ~]# yum-co nfi g -manag er --enabl e exampl e\* Loaded plugins: langpacks, product-id, subscription-manager ============================== repo: example ============================== [example] bandwidth = 0 base_persistdir = /var/lib/yum/repos/x86_64/6Server baseurl = http://www.example.com/repo/6Server/x86_64/ cache = 0 cachedir = /var/cache/yum/x86_64/6Server/example [output truncated] When successful, the yum-co nfi g -manag er --enabl e command displays the current repository configuration. Disabling a Yum Re po sit o ry To disable a yum repository, run the following command as ro o t: yum-co nfi g -manag er --d i sabl e repository… …where repository is the unique repository ID (use yum repo l i st al l to list available repository ID s). Similarly to yum-co nfi g -manag er --enabl e, you can use a glob expression to disable all matching repositories at the same time: yum-co nfi g -manag er --d i sabl e glob_expression… When successful, the yum-co nfi g -manag er --d i sabl e command displays the current configuration. 77 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 7.5.6. Creat ing a Yum Reposit ory To set up a yum repository, follow these steps: 1. Install the createrepo package. To do so, type the following at a shell prompt as ro o t: yum i nstal l createrepo 2. Copy all packages that you want to have in your repository into one directory, such as /mnt/l o cal _repo /. 3. Change to this directory and run the following command: createrepo --d atabase /mnt/l o cal _repo This creates the necessary metadata for your yum repository, as well as the sq lit e database for speeding up yum operations. 7.5.7. Adding t he Opt ional and Supplement ary Reposit ories The Optional and Supplementary subscription channels provide additional software packages for Red Hat Enterprise Linux that cover open source licensed software (in the Optional channel) and proprietary licensed software (in the Supplementary channel). Before subscribing to the Optional and Supplementary channels see the Scope of Coverage D etails. If you decide to install packages from these channels, follow the steps documented in the article called How to access Optional and Supplementary channels, and -devel packages using Red Hat Subscription Manager (RHSM)? on the Red Hat Customer Portal. 7.6. Yum Plug-ins Yum provides plug-ins that extend and enhance its operations. Certain plug-ins are installed by default. Yum always informs you which plug-ins, if any, are loaded and active whenever you call any yum command. For example: ~]# yum i nfo yum Loaded plugins: langpacks, product-id, subscription-manager [output truncated] Note that the plug-in names which follow Lo ad ed pl ug i ns are the names you can provide to the -d i sabl epl ug i n= plugin_name option. 7.6.1. Enabling, Configuring, and Disabling Yum Plug-ins To enable yum plug-ins, ensure that a line beginning with pl ug i ns= is present in the [mai n] section of /etc/yum. co nf, and that its value is 1: plugins=1 You can disable all plug-ins by changing this line to pl ug i ns= 0 . 78 Chapt er 7 . Yum Important D isabling all plug-ins is not advised because certain plug-ins provide important yum services. In particular, the p ro d u ct - id and su b scrip t io n - man ag er plug-ins provide support for the certificate-based C o ntent D el i very Netwo rk (CD N). D isabling plug-ins globally is provided as a convenience option, and is generally only recommended when diagnosing a potential problem with yum. Every installed plug-in has its own configuration file in the /etc/yum/pl ug i nco nf. d / directory. You can set plug-in specific options in these files. For example, here is the aliases plug-in's al i ases. co nf configuration file: [main] enabled=1 Similar to the /etc/yum. co nf file, the plug-in configuration files always contain a [mai n] section where the enabl ed = option controls whether the plug-in is enabled when you run yum commands. If this option is missing, you can add it manually to the file. If you disable all plug-ins by setting enabl ed = 0 in /etc/yum. co nf, then all plug-ins are disabled regardless of whether they are enabled in their individual configuration files. If you merely want to disable all yum plug-ins for a single yum command, use the --no pl ug i ns option. If you want to disable one or more yum plug-ins for a single yum command, add the -d i sabl epl ug i n= plugin_name option to the command. For example, to disable the aliases plugin while updating a system, type: ~]# yum upd ate --d i sabl epl ug i n= al i ases The plug-in names you provide to the --d i sabl epl ug i n= option are the same names listed after the Lo ad ed pl ug i ns line in the output of any yum command. You can disable multiple plug-ins by separating their names with commas. In addition, you can match multiple plug-in names or shorten long ones by using glob expressions: ~]# yum upd ate --d i sabl epl ug i n= al i ases, l ang * 7.6.2. Inst alling Addit ional Yum Plug-ins Yum plug-ins usually adhere to the yum-pl ug i n-plugin_name package-naming convention, but not always: the package which provides the kab i plug-in is named kabi -yum-pl ug i ns, for example. You can install a yum plug-in in the same way you install other packages. For instance, to install the yu m- aliases plug-in, type the following at a shell prompt: ~]# yum i nstal l yum-pl ug i n-al i ases 7.6.3. Working wit h Yum Plug-ins The following list provides descriptions and usage instructions for several useful yum plug-ins. Plugins are listed by names, brackets contain the name of the package. 79 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide kab i ( kabi-yum-plugins) The kab i plug-in checks whether a driver update package conforms with the official Red Hat kernel Application Binary Interface (kABI). With this plug-in enabled, when a user attempts to install a package that uses kernel symbols which are not on a whitelist, a warning message is written to the system log. Additionally, configuring the plug-in to run in enforcing mode prevents such packages from being installed at all. To configure the kab i plug-in, edit the configuration file located in /etc/yum/pl ug i nco nf. d /kabi . co nf. A list of directives that can be used in the [mai n] section is shown in the following table. T ab le 7.3. Su p p o rt ed kabi . co nf d irect ives D irect ive D escrip t io n enabl ed =value Allows you to enable or disable the plug-in. The value must be either 1 (enabled), or 0 (disabled). When installed, the plug-in is enabled by default. whi tel i sts=directory Allows you to specify the directory in which the files with supported kernel symbols are located. By default, the kab i plug-in uses files provided by the kernel-abi-whitelists package (that is, the /l i b/mo d ul es/kabi -rhel 70 / directory). enfo rce=value Allows you to enable or disable enforcing mode. The value must be either 1 (enabled), or 0 (disabled). By default, this option is commented out and the kab i plug-in only displays a warning message. p ro d u ct - id ( subscription-manager) The p ro d u ct - id plug-in manages product identity certificates for products installed from the Content D elivery Network. The p ro d u ct - id plug-in is installed by default. lan g p acks ( yum-langpacks) The lan g p acks plug-in is used to search for locale packages of a selected language for every package that is installed. The lan g p acks plug-in is installed by default. aliases ( yum-plugin-aliases) The aliases plug-in adds the al i as command-line option which enables configuring and using aliases for yum commands. yu m- ch an g elo g ( yum-plugin-changelog) The yu m- ch an g elo g plug-in adds the --chang el o g command-line option that enables viewing package change logs before and after updating. yu m- t mp rep o ( yum-plugin-tmprepo) The yu m- t mp rep o plug-in adds the --tmprepo command-line option that takes the URL of a repository file, downloads and enables it for only one transaction. This plug-in tries to ensure the safe temporary usage of repositories. By default, it does not allow to disable the gpg check. yu m- verif y ( yum-plugin-verify) The yu m- verif y plug-in adds the veri fy, veri fy-rpm, and veri fy-al l command-line options for viewing verification data on the system. 80 Chapt er 7 . Yum yu m- versio n lo ck ( yum-plugin-versionlock) The yu m- versio n lo ck plug-in excludes other versions of selected packages, which enables protecting packages from being updated by newer versions. With the versi o nl o ck command-line option, you can view and edit the list of locked packages. 7.7. Addit ional Resources For more information on how to manage software packages on Red Hat Enterprise Linux, see the resources listed below. Inst alled Document at ion yum(8) — The manual page for the yum command-line utility provides a complete list of supported options and commands. yumd b(8) — The manual page for the yumd b command-line utility documents how to use this tool to query and, if necessary, alter the yum database. yum. co nf(5) — The manual page named yum. co nf documents available yum configuration options. yum-uti l s(1) — The manual page named yum-uti l s lists and briefly describes additional utilities for managing yum configuration, manipulating repositories, and working with yum database. Online Document at ion Yum Guides — The Yum Guides page on the project home page provides links to further documentation. See Also Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. Appendix A, RPM describes the R PM Packag e Man ag er (RPM), the packaging system used by Red Hat Enterprise Linux. 81 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Part IV. Infrastructure Services This part provides information on how to configure services and daemons and enable remote access to a Red Hat Enterprise Linux machine. 82 Chapt er 8 . Managing Services wit h syst emd Chapter 8. Managing Services with systemd 8.1. Int roduct ion t o syst emd Syst emd is a system and service manager for Linux operating systems. It is designed to be backwards compatible with SysV init scripts, and provides a number of features such as parallel startup of system services at boot time, on-demand activation of daemons, support for system state snapshots, or dependency-based service control logic. In Red Hat Enterprise Linux 7, systemd replaces Upstart as the default init system. Systemd introduces the concept of systemd units. These units are represented by unit configuration files located in one of the directories listed in Table 8.2, “ Systemd Unit Locations” , and encapsulate information about system services, listening sockets, saved system state snapshots, and other objects that are relevant to the init system. For a complete list of available systemd unit types, see Table 8.1, “ Available systemd Unit Types” . T ab le 8.1. Availab le syst emd U n it T yp es U n it T yp e File Ext en sio n D escrip t io n Service unit Target unit Automount unit D evice unit Mount unit Path unit Scope unit Slice unit . servi ce . targ et . auto mo unt . d evi ce . mo unt . path . sco pe . sl i ce Snapshot unit Socket unit Swap unit Timer unit . snapsho t . so cket . swap . ti mer A system service. A group of systemd units. A file system automount point. A device file recognized by the kernel. A file system mount point. A file or directory in a file system. An externally created process. A group of hierarchically organized units that manage system processes. A saved state of the systemd manager. An inter-process communication socket. A swap device or a swap file. A systemd timer. T ab le 8.2. Syst emd U n it Lo cat io n s D irect o ry D escrip t io n /usr/l i b/systemd /system/ /run/systemd /system/ Systemd units distributed with installed RPM packages. Systemd units created at run time. This directory takes precedence over the directory with installed service units. Systemd units created and managed by the system administrator. This directory takes precedence over the directory with runtime units. /etc/systemd /system/ 8.1.1. Main Feat ures In Red Hat Enterprise Linux 7, the systemd system and service manager provides the following main features: Socket-based activation — At boot time, systemd creates listening sockets for all system services that support this type of activation, and passes the sockets to these services as soon as they are started. This not only allows systemd to start services in parallel, but also makes it possible to restart a service without losing any message sent to it while it is unavailable: the corresponding 83 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide socket remains accessible and all messages are queued. Systemd uses socket units for socket-based activation. Bus-based activation — System services that use D -Bus for inter-process communication can be started on-demand the first time a client application attempts to communicate with them. Systemd uses D-Bus service files for bus-based activation. Device-based activation — System services that support device-based activation can be started ondemand when a particular type of hardware is plugged in or becomes available. Systemd uses device units for device-based activation. Path-based activation — System services that support path-based activation can be started ondemand when a particular file or directory changes its state. Systemd uses path units for pathbased activation. System state snapshots — Systemd can temporarily save the current state of all units or restore a previous state of the system from a dynamically created snapshot. To store the current state of the system, systemd uses dynamically created snapshot units. Mount and automount point management — Systemd monitors and manages mount and automount points. Systemd uses mount units for mount points and automount units for automount points. Aggressive parallelization — Because of the use of socket-based activation, systemd can start system services in parallel as soon as all listening sockets are in place. In combination with system services that support on-demand activation, parallel activation significantly reduces the time required to boot the system. Transactional unit activation logic — Before activating or deactivating a unit, systemd calculates its dependencies, creates a temporary transaction, and verifies that this transaction is consistent. If a transaction is inconsistent, systemd automatically attempts to correct it and remove non-essential jobs from it before reporting an error. Backwards compatibility with SysV init — Systemd fully supports SysV init scripts as described in the Linux Standard Base Core Specification, which eases the upgrade path to systemd service units. 8.1.2. Compat ibilit y Changes The systemd system and service manager is designed to be mostly compatible with SysV init and Upstart. The following are the most notable compatibility changes with regards to the previous major release of the Red Hat Enterprise Linux system: Systemd has only limited support for runlevels. It provides a number of target units that can be directly mapped to these runlevels and for compatibility reasons, it is also distributed with the earlier runl evel command. Not all systemd targets can be directly mapped to runlevels, however, and as a consequence, this command might return N to indicate an unknown runlevel. It is recommended that you avoid using the runl evel command if possible. For more information about systemd targets and their comparison with runlevels, see Section 8.3, “ Working with systemd Targets” . The systemctl utility does not support custom commands. In addition to standard commands such as start, sto p, and status, authors of SysV init scripts could implement support for any number of arbitrary commands in order to provide additional functionality. For example, the init script for i ptabl es in Red Hat Enterprise Linux 6 could be executed with the pani c command, which immediately enabled panic mode and reconfigured the system to start dropping all incoming and outgoing packets. This is not supported in systemd and the systemctl only accepts documented commands. 84 Chapt er 8 . Managing Services wit h syst emd For more information about the systemctl utility and its comparison with the earlier servi ce utility, see Section 8.2, “ Managing System Services” . The systemctl utility does not communicate with services that have not been started by systemd. When systemd starts a system service, it stores the ID of its main process in order to keep track of it. The systemctl utility then uses this PID to query and manage the service. Consequently, if a user starts a particular daemon directly on the command line, systemctl is unable to determine its current status or stop it. Systemd stops only running services. Previously, when the shutdown sequence was initiated, Red Hat Enterprise Linux 6 and earlier releases of the system used symbolic links located in the /etc/rc0 . d / directory to stop all available system services regardless of their status. With systemd, only running services are stopped on shutdown. System services are unable to read from the standard input stream. When systemd starts a service, it connects its standard input to /d ev/nul l to prevent any interaction with the user. System services do not inherit any context (such as the HO ME and P AT H environment variables) from the invoking user and their session. Each service runs in a clean execution context. When loading a SysV init script, systemd reads dependency information encoded in the Linux Standard Base (LSB) header and interprets it at run time. All operations on service units are subject to a timeout of 5 minutes to prevent a malfunctioning service from freezing the system. For a detailed list of compatibility changes introduced with systemd, see the Migration Planning Guide for Red Hat Enterprise Linux 7. 8.2. Managing Syst em Services Previous versions of Red Hat Enterprise Linux, which were distributed with SysV init or Upstart, used init scripts located in the /etc/rc. d /i ni t. d / directory. These init scripts were typically written in Bash, and allowed the system administrator to control the state of services and daemons in their system. In Red Hat Enterprise Linux 7, these init scripts have been replaced with service units. Service units end with the . servi ce file extension and serve a similar purpose as init scripts. To view, start, stop, restart, enable, or disable system services, use the systemctl command as described in Table 8.3, “ Comparison of the service Utility with systemctl ” , Table 8.4, “ Comparison of the chkconfig Utility with systemctl” , and in the section below. The servi ce and chkco nfi g commands are still available in the system and work as expected, but are only included for compatibility reasons and should be avoided. 85 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note For clarity, all examples in the rest of this section use full unit names with the . servi ce file extension, for example: ~]# systemctl sto p bl ueto o th. servi ce When working with system services, it is possible to omit this file extension to reduce typing: when the systemctl utility encounters a unit name without a file extension, it automatically assumes it is a service unit. The following command is equivalent to the one above: ~]# systemctl sto p bl ueto o th T ab le 8.3. C o mp ariso n o f t h e service U t ilit y wit h syst emct l service servi ce name servi ce name servi ce name servi ce name co nd restart servi ce name servi ce name start sto p restart rel o ad status syst emct l D escrip t io n systemctl start name. servi ce systemctl sto p name. servi ce systemctl restart name. servi ce systemctl try-restart name. servi ce systemctl rel o ad name. servi ce systemctl status name. servi ce Starts a service. Stops a service. Restarts a service. Restarts a service only if it is running. Reloads configuration. Checks if a service is running. systemctl i s-acti ve name. servi ce servi ce --status-al l systemctl l i st-uni ts --type servi ce --al l D isplays the status of all services. T ab le 8.4 . C o mp ariso n o f t h e ch kco n f ig U t ilit y wit h syst emct l ch kco n f ig syst emct l D escrip t io n chkco nfi g name o n chkco nfi g name o ff chkco nfi g --l i st name systemctl enabl e name. servi ce systemctl d i sabl e name. servi ce systemctl status name. servi ce Enables a service. D isables a service. Checks if a service is enabled. chkco nfi g --l i st systemctl l i st-uni t-fi l es --type servi ce systemctl i s-enabl ed name. servi ce 8.2.1. List ing Services To list all currently loaded service units, type the following at a shell prompt: systemctl l i st-uni ts --type servi ce 86 Lists all services and checks if they are enabled. Chapt er 8 . Managing Services wit h syst emd For each service unit, this command displays its full name (UNIT ) followed by a note whether the unit has been loaded (LO AD ), its high-level (AC T IVE) and low-level (SUB) unit activation state, and a short description (D ESC R IP T IO N). By default, the systemctl l i st-uni ts command displays only active units. If you want to list all loaded units regardless of their state, run this command with the --al l or -a command line option: systemctl l i st-uni ts --type servi ce --al l You can also list all available service units to see if they are enabled. To do so, type: systemctl l i st-uni t-fi l es --type servi ce For each service unit, this command displays its full name (UNIT FILE) followed by information whether the service unit is enabled or not (ST AT E). For information on how to determine the status of individual service units, see Section 8.2.2, “ D isplaying Service Status” . Examp le 8.1. List in g Services To list all currently loaded service units, run the following command: ~]$ systemctl l i st-uni ts --type servi ce UNIT LOAD ACTIVE abrt-ccpp.service loaded active coredump hook abrt-oops.service loaded active watcher abrt-vmcore.service loaded active for ABRT abrt-xorg.service loaded active watcher abrtd.service loaded active Bug Reporting Tool ... systemd-vconsole-setup.service loaded active Console tog-pegasus.service loaded active Server SUB exited DESCRIPTION Install ABRT running ABRT kernel log exited Harvest vmcores running ABRT Xorg log running ABRT Automated exited Setup Virtual running OpenPegasus CIM LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 4 6 l o ad ed uni ts l i sted . Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files' To list all installed service units to determine if they are enabled, type: ~]$ systemctl l i st-uni t-fi l es --type servi ce UNIT FILE STATE abrt-ccpp.service enabled 87 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide abrt-oops.service abrt-vmcore.service abrt-xorg.service abrtd.service ... wpa_supplicant.service ypbind.service enabled enabled enabled enabled disabled disabled 208 unit files listed. 8.2.2. Displaying Service St at us To display detailed information about a service unit that corresponds to a system service, type the following at a shell prompt: systemctl status name. servi ce Replace name with the name of the service unit you want to inspect (for example, g d m). This command displays the name of the selected service unit followed by its short description, one or more fields described in Table 8.5, “ Available Service Unit Information” , and if it is executed by the ro o t user, also the most recent log entries. T ab le 8.5. Availab le Service U n it In f o rmat io n Field D escrip t io n Lo ad ed Information whether the service unit has been loaded, the absolute path to the unit file, and a note whether the unit is enabled. Information whether the service unit is running followed by a time stamp. The PID of the corresponding system service followed by its name. Additional information about the corresponding system service. Additional information about related processes. Additional information about related Control Groups. Acti ve Mai n P ID Status P ro cess C G ro up To only verify that a particular service unit is running, run the following command: systemctl i s-acti ve name. servi ce Similarly, to determine whether a particular service unit is enabled, type: systemctl i s-enabl ed name. servi ce Note that both systemctl i s-acti ve and systemctl i s-enabl ed return an exit status of 0 if the specified service unit is running or enabled. For information on how to list all currently loaded service units, see Section 8.2.1, “ Listing Services” . Examp le 8.2. D isp layin g Service St at u s The service unit for the GNOME D isplay Manager is named g d m. servi ce. To determine the current status of this service unit, type the following at a shell prompt: 88 Chapt er 8 . Managing Services wit h syst emd ~]# systemctl status g d m. servi ce gdm.service - GNOME Display Manager Loaded: loaded (/usr/lib/systemd/system/gdm.service; enabled) Active: active (running) since Thu 2013-10-17 17:31:23 CEST; 5min ago Main PID: 1029 (gdm) CGroup: /system.slice/gdm.service ├─1029 /usr/sbin/gdm ├─1037 /usr/libexec/gdm-simple-slave --display-id /org/gno... └─1047 /usr/bin/Xorg :0 -background none -verbose -auth /r... Oct 17 17:31:23 localhost systemd[1]: Started GNOME Display Manager. 8.2.3. St art ing a Service To start a service unit that corresponds to a system service, type the following at a shell prompt as ro o t: systemctl start name. servi ce Replace name with the name of the service unit you want to start (for example, g d m). This command starts the selected service unit in the current session. For information on how to enable a service unit to be started at boot time, see Section 8.2.6, “ Enabling a Service” . For information on how to determine the status of a certain service unit, see Section 8.2.2, “ D isplaying Service Status” . Examp le 8.3. St art in g a Service The service unit for the Apache HTTP Server is named httpd . servi ce. To activate this service unit and start the httpd daemon in the current session, run the following command as ro o t: ~]# systemctl start httpd . servi ce 8.2.4 . St opping a Service To stop a service unit that corresponds to a system service, type the following at a shell prompt as ro o t: systemctl sto p name. servi ce Replace name with the name of the service unit you want to stop (for example, bl ueto o th). This command stops the selected service unit in the current session. For information on how to disable a service unit and prevent it from being started at boot time, see Section 8.2.7, “ D isabling a Service” . For information on how to determine the status of a certain service unit, see Section 8.2.2, “ D isplaying Service Status” . Examp le 8.4 . St o p p in g a Service 89 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The service unit for the bl ueto o thd daemon is named bl ueto o th. servi ce. To deactivate this service unit and stop the bl ueto o thd daemon in the current session, run the following command as ro o t: ~]# systemctl sto p bl ueto o th. servi ce 8.2.5. Rest art ing a Service To restart a service unit that corresponds to a system service, type the following at a shell prompt as ro o t: systemctl restart name. servi ce Replace name with the name of the service unit you want to restart (for example, httpd ). This command stops the selected service unit in the current session and immediately starts it again. Importantly, if the selected service unit is not running, this command starts it too. To tell systemd to restart a service unit only if the corresponding service is already running, run the following command as ro o t: systemctl try-restart name. servi ce Certain system services also allow you to reload their configuration without interrupting their execution. To do so, type as ro o t: systemctl rel o ad name. servi ce Note that system services that do not support this feature ignore this command altogether. For convenience, the systemctl command also supports the rel o ad -o r-restart and rel o ad -o rtry-restart commands that restart such services instead. For information on how to determine the status of a certain service unit, see Section 8.2.2, “ D isplaying Service Status” . Examp le 8.5. R est art in g a Service In order to prevent users from encountering unnecessary error messages or partially rendered web pages, the Apache HTTP Server allows you to edit and reload its configuration without the need to restart it and interrupt actively processed requests. To do so, type the following at a shell prompt as ro o t: ~]# systemctl rel o ad httpd . servi ce 8.2.6. Enabling a Service To configure a service unit that corresponds to a system service to be automatically started at boot time, type the following at a shell prompt as ro o t: systemctl enabl e name. servi ce Replace name with the name of the service unit you want to enable (for example, httpd ). This command reads the [Instal l ] section of the selected service unit and creates appropriate symbolic links to the /usr/l i b/systemd /system/name. servi ce file in the 90 Chapt er 8 . Managing Services wit h syst emd /etc/systemd /system/ directory and its subdirectories. This command does not, however, rewrite links that already exist. If you want to ensure that the symbolic links are re-created, use the following command as ro o t: systemctl reenabl e name. servi ce This command disables the selected service unit and immediately enables it again. For information on how to determine whether a certain service unit is enabled to start at boot time, see Section 8.2.2, “ D isplaying Service Status” . For information on how to start a service in the current session, see Section 8.2.3, “ Starting a Service” . Examp le 8.6 . En ab lin g a Service To configure the Apache HTTP Server to start automatically at boot time, run the following command as ro o t: ~]# systemctl enabl e httpd . servi ce ln -s '/usr/lib/systemd/system/httpd.service' '/etc/systemd/system/multi-user.target.wants/httpd.service' 8.2.7. Disabling a Service To prevent a service unit that corresponds to a system service from being automatically started at boot time, type the following at a shell prompt as ro o t: systemctl d i sabl e name. servi ce Replace name with the name of the service unit you want to disable (for example, bl ueto o th). This command reads the [Instal l ] section of the selected service unit and removes appropriate symbolic links to the /usr/l i b/systemd /system/name. servi ce file from the /etc/systemd /system/ directory and its subdirectories. In addition, you can mask any service unit to prevent it from being started manually or by another service. To do so, run the following command as ro o t: systemctl mask name. servi ce This command replaces the /etc/systemd /system/name. servi ce file with a symbolic link to /d ev/nul l , rendering the actual unit file inaccessible to systemd. To revert this action and unmask a service unit, type as ro o t: systemctl unmask name. servi ce For information on how to determine whether a certain service unit is enabled to start at boot time, see Section 8.2.2, “ D isplaying Service Status” . For information on how to stop a service in the current session, see Section 8.2.4, “ Stopping a Service” . Examp le 8.7. D isab lin g a Service Example 8.4, “ Stopping a Service” illustrates how to stop the bl ueto o th. servi ce unit in the current session. To prevent this service unit from starting at boot time, type the following at a shell prompt as ro o t: 91 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# systemctl d i sabl e bl ueto o th. servi ce rm '/etc/systemd/system/dbus-org.bluez.service' rm '/etc/systemd/system/bluetooth.target.wants/bluetooth.service' 8.3. Working wit h syst emd T arget s Previous versions of Red Hat Enterprise Linux, which were distributed with SysV init or Upstart, implemented a predefined set of runlevels that represented specific modes of operation. These runlevels were numbered from 0 to 6 and were defined by a selection of system services to be run when a particular runlevel was enabled by the system administrator. In Red Hat Enterprise Linux 7, the concept of runlevels has been replaced with systemd targets. Systemd targets are represented by target units. Target units end with the . targ et file extension and their only purpose is to group together other systemd units through a chain of dependencies. For example, the g raphi cal . targ et unit, which is used to start a graphical session, starts system services such as the GNOME D isplay Manager (g d m. servi ce) or Accounts Service (acco untsd aemo n. servi ce) and also activates the mul ti -user. targ et unit. Similarly, the mul ti user. targ et unit starts other essential system services such as NetworkManager (Netwo rkManag er. servi ce) or D -Bus (d bus. servi ce) and activates another target unit named basi c. targ et. Red Hat Enterprise Linux 7 is distributed with a number of predefined targets that are more or less similar to the standard set of runlevels from the previous releases of this system. For compatibility reasons, it also provides aliases for these targets that directly map them to SysV runlevels. Table 8.6, “ Comparison of SysV Runlevels with systemd Targets” provides a complete list of SysV runlevels and their corresponding systemd targets. T ab le 8.6 . C o mp ariso n o f SysV R u n levels wit h syst emd T arg et s R u n level T arg et U n it s D escrip t io n 0 runl evel 0 . targ et, po wero ff. targ et runl evel 1. targ et, rescue. targ et runl evel 2. targ et, mul ti user. targ et runl evel 3. targ et, mul ti user. targ et runl evel 4 . targ et, mul ti user. targ et runl evel 5. targ et, g raphi cal . targ et runl evel 6 . targ et, rebo o t. targ et Shut down and power off the system. 1 2 3 4 5 6 Set up a rescue shell. Set up a non-graphical multi-user system. Set up a non-graphical multi-user system. Set up a non-graphical multi-user system. Set up a graphical multi-user system. Shut down and reboot the system. To view, change, or configure systemd targets, use the systemctl utility as described in Table 8.7, “ Comparison of SysV init Commands with systemctl” and in the sections below. The runl evel and tel i ni t commands are still available in the system and work as expected, but are only included for compatibility reasons and should be avoided. T ab le 8.7. C o mp ariso n o f SysV in it C o mman d s wit h syst emct l O ld C o mman d 92 N ew C o mman d D escrip t io n Chapt er 8 . Managing Services wit h syst emd O ld C o mman d N ew C o mman d D escrip t io n runl evel systemctl l i st-uni ts --type targ et systemctl i so l ate name. targ et Lists currently loaded target units. Changes the current target. tel i ni t runlevel 8.3.1. Viewing t he Default T arget To determine which target unit is used by default, run the following command: systemctl g et-d efaul t This command resolves the symbolic link located at /etc/systemd /system/d efaul t. targ et and displays the result. For information on how to change the default target, see Section 8.3.3, “ Changing the D efault Target” . For information on how to list all currently loaded target units, see Section 8.3.2, “ Viewing the Current Target” . Examp le 8.8. Viewin g t h e D ef au lt T arg et To display the default target unit, type: ~]$ systemctl g et-d efaul t graphical.target 8.3.2. Viewing t he Current T arget To list all currently loaded target units, type the following command at a shell prompt: systemctl l i st-uni ts --type targ et For each target unit, this commands displays its full name (UNIT ) followed by a note whether the unit has been loaded (LO AD ), its high-level (AC T IVE) and low-level (SUB) unit activation state, and a short description (D ESC R IP T IO N). By default, the systemctl l i st-uni ts command displays only active units. If you want to list all loaded units regardless of their state, run this command with the --al l or -a command line option: systemctl l i st-uni ts --type targ et --al l See Section 8.3.1, “ Viewing the D efault Target” for information on how to display the default target. For information on how to change the current target, see Section 8.3.4, “ Changing the Current Target” . Examp le 8.9 . Viewin g t h e C u rren t T arg et To list all currently loaded target units, run the following command: ~]$ systemctl l i st-uni ts --type targ et UNIT LOAD ACTIVE SUB DESCRIPTION basic.target loaded active active Basic System cryptsetup.target loaded active active Encrypted Volumes 93 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide getty.target graphical.target local-fs-pre.target local-fs.target multi-user.target network.target paths.target remote-fs.target sockets.target sound.target spice-vdagentd.target guests swap.target sysinit.target time-sync.target timers.target loaded loaded loaded loaded loaded loaded loaded loaded loaded loaded loaded active active active active active active active active active active active active active active active active active active active active active active Login Prompts Graphical Interface Local File Systems (Pre) Local File Systems Multi-User System Network Paths Remote File Systems Sockets Sound Card Agent daemon for Spice loaded loaded loaded loaded active active active active active active active active Swap System Initialization System Time Synchronized Timers LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 17 l o ad ed uni ts l i sted . Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'. 8.3.3. Changing t he Default T arget To configure the system to use a different target unit by default, type the following at a shell prompt as ro o t: systemctl set-d efaul t name. targ et Replace name with the name of the target unit you want to use by default (for example, mul ti -user). This command replaces the /etc/systemd /system/d efaul t. targ et file with a symbolic link to /usr/l i b/systemd /system/name. targ et, where name is the name of the target unit you want to use. For information on how to change the current target, see Section 8.3.4, “ Changing the Current Target” . For information on how to list all currently loaded target units, see Section 8.3.2, “ Viewing the Current Target” . Examp le 8.10. C h an g in g t h e D ef au lt T arg et To configure the system to use the mul ti -user. targ et unit by default, run the following command as ro o t: ~]# systemctl set-d efaul t mul ti -user. targ et rm '/etc/systemd/system/default.target' ln -s '/usr/lib/systemd/system/multi-user.target' '/etc/systemd/system/default.target' 94 Chapt er 8 . Managing Services wit h syst emd 8.3.4 . Changing t he Current T arget To change to a different target unit in the current session, type the following at a shell prompt as ro o t: systemctl i so l ate name. targ et Replace name with the name of the target unit you want to use (for example, mul ti -user). This command starts the target unit named name and all dependent units, and immediately stops all others. For information on how to change the default target, see Section 8.3.3, “ Changing the D efault Target” . For information on how to list all currently loaded target units, see Section 8.3.2, “ Viewing the Current Target” . Examp le 8.11. C h an g in g t h e C u rren t T arg et To turn off the graphical user interface and change to the mul ti -user. targ et unit in the current session, run the following command as ro o t: ~]# systemctl i so l ate mul ti -user. targ et 8.3.5. Changing t o Rescue Mode Rescue mode provides a convenient single-user environment and allows you to repair your system in situations when it is unable to complete a regular booting process. In rescue mode, the system attempts to mount all local file systems and start some important system services, but it does not activate network interfaces or allow more users to be logged into the system at the same time. In Red Hat Enterprise Linux 7, rescue mode is equivalent to single user mode and requires the root password. To change the current target and enter rescue mode in the current session, type the following at a shell prompt as ro o t: systemctl rescue This command is similar to systemctl i so l ate rescue. targ et, but it also sends an informative message to all users that are currently logged into the system. To prevent systemd from sending this message, run this command with the --no -wal l command line option: systemctl --no -wal l rescue For information on how to enter emergency mode, see Section 8.3.6, “ Changing to Emergency Mode” . Examp le 8.12. C h an g in g t o R escu e Mo d e To enter rescue mode in the current session, run the following command as ro o t: ~]# systemctl rescue Broadcast message from root@ localhost on pts/0 (Fri 2013-10-25 18:23:15 CEST): 95 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The system is going down to rescue mode NOW! 8.3.6. Changing t o Emergency Mode Emergency mode provides the most minimal environment possible and allows you to repair your system even in situations when the system is unable to enter rescue mode. In emergency mode, the system mounts the root file system only for reading, does not attempt to mount any other local file systems, does not activate network interfaces, and only starts few essential services. In Red Hat Enterprise Linux 7, emergency mode requires the root password. To change the current target and enter emergency mode, type the following at a shell prompt as ro o t: systemctl emerg ency This command is similar to systemctl i so l ate emerg ency. targ et, but it also sends an informative message to all users that are currently logged into the system. To prevent systemd from sending this message, run this command with the --no -wal l command line option: systemctl --no -wal l emerg ency For information on how to enter rescue mode, see Section 8.3.5, “ Changing to Rescue Mode” . Examp le 8.13. C h an g in g t o Emerg en cy Mo d e To enter emergency mode without sending a message to all users that are currently logged into the system, run the following command as ro o t: ~]# systemctl --no -wal l emerg ency 8.4 . Shut t ing Down, Suspending, and Hibernat ing t he Syst em In Red Hat Enterprise Linux 7, the systemctl utility replaces a number of power management commands used in previous versions of the Red Hat Enterprise Linux system. The commands listed in Table 8.8, “ Comparison of Power Management Commands with systemctl” are still available in the system for compatibility reasons, but it is advised that you use systemctl when possible. T ab le 8.8. C o mp ariso n o f Po wer Man ag emen t C o mman d s wit h syst emct l O ld C o mman d N ew C o mman d D escrip t io n hal t po wero ff rebo o t pm-suspend pm-hi bernate pm-suspend -hybri d systemctl systemctl systemctl systemctl systemctl systemctl sl eep Halts the system. Powers off the system. Restarts the system. Suspends the system. Hibernates the system. Hibernates and suspends the system. 96 hal t po wero ff rebo o t suspend hi bernate hybri d - Chapt er 8 . Managing Services wit h syst emd 8.4 .1. Shut t ing Down t he Syst em To shut down the system and power off the machine, type the following at a shell prompt as ro o t: systemctl po wero ff To shut down and halt the system without powering off the machine, run the following command as ro o t: systemctl hal t By default, running either of these commands causes systemd to send an informative message to all users that are currently logged into the system. To prevent systemd from sending this message, run the selected command with the --no -wal l command line option, for example: systemctl --no -wal l po wero ff 8.4 .2. Rest art ing t he Syst em To restart the system, run the following command as ro o t: systemctl rebo o t By default, this command causes systemd to send an informative message to all users that are currently logged into the system. To prevent systemd from sending this message, run this command with the --no -wal l command line option: systemctl --no -wal l rebo o t 8.4 .3. Suspending t he Syst em To suspend the system, type the following at a shell prompt as ro o t: systemctl suspend This command saves the system state in RAM and with the exception of the RAM module, powers off most of the devices in the machine. When you turn the machine back on, the system then restores its state from RAM without having to boot again. Because the system state is saved in RAM and not on the hard disk, restoring the system from suspend mode is significantly faster than restoring it from hibernation, but as a consequence, a suspended system state is also vulnerable to power outages. For information on how to hibernate the system, see Section 8.4.4, “ Hibernating the System” . 8.4 .4 . Hibernat ing t he Syst em To hibernate the system, type the following at a shell prompt as ro o t: systemctl hi bernate This command saves the system state on the hard disk drive and powers off the machine. When you turn the machine back on, the system then restores its state from the saved data without having to boot again. Because the system state is saved on the hard disk and not in RAM, the machine does 97 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide not have to maintain electrical power to the RAM module, but as a consequence, restoring the system from hibernation is significantly slower than restoring it from suspend mode. To hibernate and suspend the system, run the following command as ro o t: systemctl hybri d -sl eep For information on how to suspend the system, see Section 8.4.3, “ Suspending the System” . 8.5. Cont rolling syst emd on a Remot e Machine In addition to controlling the systemd system and service manager locally, the systemctl utility also allows you to interact with systemd running on a remote machine over the SSH protocol. Provided that the sshd service on the remote machine is running, you can connect to this machine by running the systemctl command with the --ho st or -H command line option: systemctl --ho st user_name@ host_name command Replace user_name with the name of the remote user, host_name with the machine's host name, and co mmand with any of the systemctl commands described above. Note that the remote machine must be configured to allow the selected user remote access over the SSH protocol. For more information on how to configure an SSH server, see Chapter 9, OpenSSH. Examp le 8.14 . R emo t e Man ag emen t To log in to a remote machine named server-0 1. exampl e. co m as the ro o t user and determine the current status of the httpd . servi ce unit, type the following at a shell prompt: ~]$ systemctl -H ro o t@ server-0 1. exampl e. co m status httpd . servi ce >>>>>>> systemd unit files -- update root@ server-01.example.com's password: httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled) Active: active (running) since Fri 2013-11-01 13:58:56 CET; 2h 48min ago Main PID: 649 Status: "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec" CGroup: /system.slice/httpd.service 8.6. Creat ing and Modifying syst emd Unit Files A unit file contains configuration directives that describe the unit and define its behavior. Several systemctl commands work with unit files in the background. To make finer adjustments, system administrator must edit or create unit files manually. Table 8.2, “ Systemd Unit Locations” lists three main directories where unit files are stored on the system, the /etc/systemd /system/ directory is reserved for unit files created or customized by the system administrator. Unit file names take the following form: unit_name.type_extension 98 Chapt er 8 . Managing Services wit h syst emd Here, unit_name stands for the name of the unit and type_extension identifies the unit type, see Table 8.1, “ Available systemd Unit Types” for a complete list of unit types. For example, there usually is sshd . servi ce as well as sshd . so cket unit present on your system. Unit files can be supplemented with a directory for additional configuration files. For example, to add custom configuration options to sshd . servi ce, create the sshd . servi ce. d /custo m. co nf file and insert additional directives there. For more information on configuration directories, see Section 8.6.4, “ Modifying Existing Unit Files” . Also, the sshd . servi ce. wants/ and sshd . servi ce. req ui res/ directories can be created. These directories contain symbolic links to unit files that are dependencies of the sshd service. The symbolic links are automatically created either during installation according to [Install] unit file options (see Table 8.11, “ Important [Install] Section Options” ) or at runtime based on [Unit] options (see Table 8.9, “ Important [Unit] Section Options” ). It is also possible to create these directories and symbolic links manually. Many unit file options can be set using the so called unit specifiers – wildcard strings that are dynamically replaced with unit parameters when the unit file is loaded. This enables creation of generic unit files that serve as templates for generating instantiated units. See Section 8.6.5, “ Working with Instantiated Units” for details. 8.6.1. Underst anding t he Unit File St ruct ure Unit files typically consist of three sections: [Unit] — contains generic options that are not dependent on the type of the unit. These options provide unit description, specify the unit's behavior, and set dependencies to other units. For a list of most frequently used [Unit] options, see Table 8.9, “ Important [Unit] Section Options” . [unit type] — if a unit has type-specific directives, these are grouped under a section named after the unit type. For example, service unit files contain the [Service] section, see Table 8.10, “ Important [Service] Section Options” for most frequently used [Service] options. [Install] — contains information about unit installation used by systemctl enabl e and d i sabl e commands, see Table 8.11, “ Important [Install] Section Options” for a list of [Install] options. T ab le 8.9 . Imp o rt an t [ U n it ] Sect io n O p t io n s O p t io n [a] D escrip t io n D escri pti o n A meaningful description of the unit. This text is displayed for example in the output of the systemctl status command. Provides a list of URIs referencing documentation for the unit. D efines the order in which units are started. The unit starts only after the units specified in After are active. Unlike R eq ui res, After does not explicitly activate the specified units. The Befo re option has the opposite functionality to After. Configures dependencies on other units. The units listed in R eq ui res are activated together with the unit. If any of the required units fail to start, the unit is not activated. Configures weaker dependencies than R eq ui res. If any of the listed units does not start successfully, it has no impact on the unit activation. This is the recommended way to establish custom unit dependencies. Configures negative dependencies, an opposite to R eq ui res. D o cumentati o n After [b ] R eq ui res Wants C o nfl i cts 99 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide O p t io n D escrip t io n [a] Fo r a c o mp lete lis t o f o p tio ns c o nfig urab le in the [Unit] s ec tio n, s ee the systemd . uni t(5) manual p ag e. [b ] In mo s t c as es , it is s uffic ient to s p ec ify jus t the o rd ering d ep end enc ies with After and Befo re unit file o p tio ns . If yo u d ec id e to s et a req uirement d ep end enc y with Wants (rec o mmend ed ) o r R eq ui res , us ually it mus t b e s up p lemented with After as o rd ering and req uirement d ep end enc ies are ind ep end ent fro m eac h o ther. No te that fo r s ake o f s imp lic ity and flexib ility, it is rec o mmend ed to us e the d ep end enc y o p tio ns reas o nab ly and ins tead rely o n tec hniq ues s uc h as b us -b as ed o r s o c ketb as ed ac tivatio n when p o s s ib le. T ab le 8.10. Imp o rt an t [ Service] Sect io n O p t io n s O p t io n [a] D escrip t io n T ype Configures the unit process startup type that affects the functionality of ExecStart and related options. One of: si mpl e – The default value. The process started with ExecStart is the main process of the service. fo rki ng – The process started with ExecStart spawns a child process that becomes the main process of the service. The parent process exits when the startup is complete. o nesho t – This type is similar to si mpl e, but the process exits before starting consequent units. d bus – This type is similar to si mpl e, but consequent units are started only after the main process gains a D -Bus name. no ti fy – This type is similar to si mpl e, but consequent units are started only after a notification message is sent via the sd_notify() function. i d l e – similar to si mpl e, the actual execution of the service binary is delayed until all jobs are finished, which avoids mixing the status output with shell output of services. Specifies commands or scripts to be executed when the unit is started. ExecStartP re and ExecStartP o st specify custom commands to be executed before and after ExecStart. T ype= o nesho t enables specifying multiple custom commands that are then executed sequentially. ExecSto p Specifies commands or scripts to be executed when the unit is stopped. ExecR el o ad Specifies commands or scripts to be executed when the unit is reloaded. R estart With this option enabled, the service is restarted after its process exits, with the exception of a clean stop by the systemctl command. R emai nAfterExi t If set to True, the service is considered active even when all its processes exited. D efault value is False. This option is especially useful if T ype= o nesho t is configured. ExecStart [a] Fo r a c o mp lete lis t o f o p tio ns c o nfig urab le in the [Servic e] s ec tio n, s ee the systemd . servi ce(5) manual p ag e. T ab le 8.11. Imp o rt an t [ In st all] Sect io n O p t io n s O p t io n [a] D escrip t io n Al i as R eq ui red By Provides a space-separated list of additional names for the unit. A list of units that depend on the unit. When this unit is enabled, the units listed in R eq ui red By gain a R eq ui re dependency on the unit. 100 Chapt er 8 . Managing Services wit h syst emd O p t io n D escrip t io n A list of units that weakly depend on the unit. When this unit is enabled, the units listed in Wanted By gain a Want dependency on the unit. Al so Specifies a list of units to be installed or uninstalled along with the unit. D efaul tInstance Limited to instantiated units, this option specifies the default instance for which the unit is enabled. See Section 8.6.5, “ Working with Instantiated Units” [a] Fo r a c o mp lete lis t o f o p tio ns c o nfig urab le in the [Ins tall] s ec tio n, s ee the systemd . uni t(5) Wanted By manual p ag e. A whole range of options that can be used to fine tune the unit configuration, Example 8.15, “ postfix.service Unit File” shows an example of a service unit installed on the system. Moreover, unit file options can be defined in a way that enables dynamic creation of units as described in Section 8.6.5, “ Working with Instantiated Units” . Examp le 8.15. p o st f ix.service U n it File What follows is the content of the /usr/l i b/systemd /system/po sti fi x. servi ce unit file as currently provided by the postfix package: [Unit] Description=Postfix Mail Transport Agent After=syslog.target network.target Conflicts=sendmail.service exim.service [Service] Type=forking PIDFile=/var/spool/postfix/pid/master.pid EnvironmentFile=-/etc/sysconfig/network ExecStartPre=-/usr/libexec/postfix/aliasesdb ExecStartPre=-/usr/libexec/postfix/chroot-update ExecStart=/usr/sbin/postfix start ExecReload=/usr/sbin/postfix reload ExecStop=/usr/sbin/postfix stop [Install] WantedBy=multi-user.target The [Unit] section describes the service, specifies the ordering dependencies, as well as conflicting units. In [Service], a sequence of custom scripts is specified to be executed during unit activation, on stop, and on reload. Envi ro nmentFi l e points to the location where environment variables for the service are defined, P ID Fi l e specifies a stable PID for the main process of the service. Finally, the [Install] section lists units that depend on the service. 8.6.2. Creat ing Cust om Unit Files There are several use cases for creating unit files from scratch: you could run a custom daemon, create a second instance of some existing service (as in Example 8.17, “ Creating a second instance of the sshd service” ), or import a SysV init script (more in Section 8.6.3, “ Converting SysV Init Scripts to Unit Files” ). On the other hand, if you intend just to modify of extend the behavior of an existing unit, use the instructions from Section 8.6.4, “ Modifying Existing Unit Files” . The following procedure describes the general process of creating a custom service: 101 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 1. Prepare the executable file with the custom service. This can be a custom-created script, or an executable delivered by a software provider. If required, prepare a PID file to hold a constant PID for the main process of the custom service. It is also possible to include environment files to store shell variables for the service. Make sure the source script is executable (by executing the chmo d a-x) and is not interactive. 2. Create a unit file in the /etc/systemd /system/ directory and make sure it has correct file permissions. Execute as ro o t: to uch /etc/systemd /system/name. servi ce chmo d 6 6 4 /etc/systemd /system/name. servi ce Replace name with a name of the service to be created. Note that file does not need to be executable. 3. Open the name. servi ce file created in the previous step, and add the service configuration options. There is a variety of options that can be used depending on the type of service you wish to create, see Section 8.6.1, “ Understanding the Unit File Structure” . The following is an example unit configuration for a network-related service: [Unit] Description=service_description After=network.target [Service] ExecStart=path_to_executable Type=forking PIDFile=path_to_pidfile [Install] WantedBy=default.target Where: service_description is an informative description that is displayed in journal log files and in the output of the systemctl status command. the After setting ensures that the service is started only after the network is running. Add a space-separated list of other relevant services or targets. path_to_executable stands for the path to the actual service executable. T ype= fo rki ng is used for daemons that make the fork system call. The main process of the service is created with the PID specified in path_to_pidfile. Find other startup types in Table 8.10, “ Important [Service] Section Options” . Wanted By states the target or targets that the service should be started under. Think of these targets as of a replacement of the older concept of runlevels, see Section 8.3, “ Working with systemd Targets” for details. 4. Notify systemd that a new name. servi ce file exists by executing the following command as ro o t: systemctl d aemo n-rel o ad systemctl start name. servi ce 102 Chapt er 8 . Managing Services wit h syst emd The name.service unit can now be managed as any other system service with commands described in Section 8.2, “ Managing System Services” . Examp le 8.16 . C reat in g t h e emacs.service File When using the Emacs text editor, it is often faster and more convenient to have it running in the background instead of starting a new instance of the program whenever editing a file. The following steps show how to create a unit file for Emacs, so that it can be handled like a service. 1. Create unit file in the /etc/systemd /system/ directory and make sure it has correct file permissions. Execute as ro o t: ~]# to uch /etc/systemd /system/emacs. servi ce ~]# chmo d 6 6 4 /etc/systemd /system/emacs. servi ce 2. Add the following content to the file: [Unit] Description=Emacs: the extensible, self-documenting text editor [Service] Type=forking ExecStart=/usr/bin/emacs --daemon ExecStop=/usr/bin/emacsclient --eval "(kill-emacs)" Environment=SSH_AUTH_SOCK=%t/keyring/ssh Restart=always [Install] WantedBy=default.target With the above configuration, the /usr/bi n/emacs executable is started in daemon mode on service start. The SSH_AUTH_SOCK environment variable is set using the " % t" unit specifier that stands for the runtime directory. The service also restarts the emacs process if it exits unexpectedly. 3. Execute the following commands to reload the configuration and start the custom service: ~]# systemctl d aemo n-rel o ad ~]# systemctl start emacs. servi ce As the editor is now registered as a systemd service, you can use all standard systemctl commands, such as systemctl status emacs to display its status systemctl enabl e emacs or to start it automatically on system boot. Examp le 8.17. C reat in g a seco n d in st an ce o f t h e ssh d service System Administrators often need to configure and run multiple instances of a service. This is done by creating copies of the original service configuration files and modifying certain parameters to avoid conflicts with the primary instance of the service. The following procedure shows how to create a second instance of the sshd service: 1. Create a copy of the sshd _co nfi g file that will be used by the second daemon: ~]# cp /etc/ssh/sshd {,-seco nd }_co nfi g 103 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 2. Edit the sshd -seco nd _co nfi g file created in the previous step to assign a different port number and PID file to the second daemon: Port 22220 PidFile /var/run/sshd-second.pid See the sshd _co nfi g (5) manual page for more information on P o rt and P i d Fi l e options. Make sure the port you choose is not in use by any other service. The PID file does not have to exist before running the service, it is generated automatically on service start. 3. Create a copy of the systemd unit file for the sshd service. ~]# cp /usr/l i b/systemd /system/sshd {,-seco nd }. servi ce 4. Alter the sshd -seco nd . servi ce created in the previous step as follows: a. Modify the D escri pti o n option: Description=OpenSSH server second instance daemon b. Add sshd.service to services specified in the After option, so that the second instance starts only after the first one has already started: After=syslog.target network.target auditd.service sshd.service c. The first instance of sshd includes key generation, therefore remove the ExecStartPre=/usr/sbin/sshd-keygen line. d. Add the -f /etc/ssh/sshd -seco nd _co nfi g parameter to the sshd command, so that the alternative configuration file is used: ExecStart=/usr/sbin/sshd -D -f /etc/ssh/sshd-second_config $OPTIONS e. After the above modifications, the sshd-second.service should look as follows: [Unit] Description=OpenSSH server second instance daemon After=syslog.target network.target auditd.service sshd.service [Service] EnvironmentFile=/etc/sysconfig/sshd ExecStart=/usr/sbin/sshd -D -f /etc/ssh/sshd-second_config $OPTIONS ExecReload=/bin/kill -HUP $MAINPID KillMode=process Restart=on-failure RestartSec=42s [Install] WantedBy=multi-user.target 104 Chapt er 8 . Managing Services wit h syst emd 5. If using SELinux, add the port for the second instance of sshd to SSH ports, otherwise the second instance of sshd will be rejected to bind to the port: ~]# semanag e po rt -a -t ssh_po rt_t -p tcp 22220 6. Enable sshd-second.service, so that it starts automatically upon boot: ~]# systemctl enabl e sshd -seco nd . servi ce Verify if the sshd-second.service is running by using the systemctl status command. Also, verify if the port is enabled correctly by connecting to the service: ~]$ ssh -p 22220 user@ server If firewall is in use, please make sure that it is configured appropriately in order to allow connections to the second instance of sshd. 8.6.3. Convert ing SysV Init Script s t o Unit Files Before taking time to convert a SysV init script to a unit file, make sure that the conversion was not already done elsewhere. All core services installed on Red Hat Enterprise Linux 7 come with default unit files, and the same applies for many third-party software packages. Converting an init script to a unit file requires analyzing the script and extracting the necessary information from it. Based on this data you can create a unit file as described in Section 8.6.2, “ Creating Custom Unit Files” . As init scripts can vary greatly depending on the type of the service, you might need to employ more configuration options for translation than outlined in this chapter. Note that some levels of customization that were available with init scripts are no longer supported by systemd units, see Section 8.1.2, “ Compatibility Changes” . The majority of information needed for conversion is provided in the script's header. The following example shows the opening section of the init script used to start the po stfi x service on Red Hat Enterprise Linux 6: #!/bin/bash # # postfix Postfix Mail Transfer Agent # # chkconfig: 2345 80 30 # description: Postfix is a Mail Transport Agent, which is the program \ # that moves mail from one machine to another. # processname: master # pidfile: /var/spool/postfix/pid/master.pid # config: /etc/postfix/main.cf # config: /etc/postfix/master.cf ### BEGIN INIT INFO # Provides: postfix MTA # Required-Start: $local_fs $network $remote_fs # Required-Stop: $local_fs $network $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: start and stop postfix 105 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide # Description: Postfix is a Mail Transport Agent, which is the program that # moves mail from one machine to another. ### END INIT INFO In the above example, only lines starting with # chkconfig and # description are mandatory, so you might not find the rest in different init files. The text enclosed between the ### BEGIN INIT INFO and ### END INIT INFO lines is called Linux Standard Base (LSB) header. If specified, LSB headers contain directives defining the service description, dependencies, and default runlevels. What follows is an overview of analytic tasks aiming to collect the data needed for a new unit file. The postfix init script is used as an example, see the resulting postfix unit file in Example 8.15, “ postfix.service Unit File” . Finding t he Se rvice De script io n Find descriptive information about the script on the line starting with #description. Use this description together with the service name in the D escri pti o n option in the [Unit] section of the unit file. The LSB header might contain similar data on the #Short-Description and #Description lines. Finding Se rvice De pe nde ncie s The LSB header might contain several directives that form dependencies between services. Most of them are translatable to systemd unit options, see Table 8.12, “ D ependency Options from the LSB Header” T ab le 8.12. D ep en d en cy O p t io n s f ro m t h e LSB H ead er LSB O p t io n D escrip t io n U n it File Eq u ivalen t P ro vi d es Specifies the boot facility name of the service, that can be referenced in other init scripts (with the " $" prefix). This is no longer needed as unit files refer to other units by their file names. Contains boot facility names of required services. This is translated as an ordering dependency, boot facility names are replaced with unit file names of corresponding services or targets they belong to. For example, in case of po stfi x, the Required-Start dependency on $network was translated to the After dependency on network.target. Constitutes waker dependencies than Required-Start. Failed Should-Start dependencies do not affect the service startup. Constitute negative dependencies. – R eq ui red -Start Sho ul d -Start R eq ui red -Sto p, Sho ul d -Sto p After, Befo re After, Befo re C o nfl i cts Finding De fault T arge t s o f t he Se rvice The line starting with #chkconfig contains three numerical values. The most important is the first number that represents the default runlevels in which the service is started. Use Table 8.6, “ Comparison of SysV Runlevels with systemd Targets” to map these runlevels to equivalent systemd targets. Then list these targets in the Wanted By option in the [Install] section of the unit file. For example, po stfi x was previously started in runlevels 2, 3, 4, and 5, which translates to multi- 106 Chapt er 8 . Managing Services wit h syst emd user.target and graphical.target on Red Hat Enterprise Linux 7. Note that the graphical.target depends on multiuser.target, therefore it is not necessary to specify both, as in Example 8.15, “ postfix.service Unit File” . You might find information on default and forbidden runlevels also at #Default-Start and #Default-Stop lines in the LSB header. The other two values specified on the #chkconfig line represent startup and shutdown priorities of the init script. These values are interpreted by systemd if it loads the init script, but there is no unit file equivalent. Finding File s Use d by t he Se rvice Init scripts require loading a function library from a dedicated directory and allow importing configuration, environment, and PID files. Environment variables are specified on the line starting with #config in the init script header, which translates to the Envi ro nmentFi l e unit file option. The PID file specified on the #pidfile init script line is imported to the unit file with the P ID Fi l e option. The key information that is not included in the init script header is the path to the service executable, and potentially some other files required by the service. In previous versions of Red Hat Enterprise Linux, init scripts used a Bash case statement to define the behavior of the service on default actions, such as start, stop, or restart, as well as custom-defined actions. The following excerpt from the po stfi x init script shows the block of code to be executed at service start. c onf_check() { [ -x /usr/sbin/postfix ] || exit 5 [ -d /etc/postfix ] || exit 6 [ -d /var/spool/postfix ] || exit 5 } m ake_aliasesdb() { if [ "$(/usr/sbin/postconf -h alias_database)" == "hash:/etc/aliases" ] then # /etc/aliases.db might be used by other MTA, make sure nothing # has touched it since our last newaliases call [ /etc/aliases -nt /etc/aliases.db ] || [ "$ALIASESDB_STAMP" -nt /etc/aliases.db ] || [ "$ALIASESDB_STAMP" -ot /etc/aliases.db ] || return /usr/bin/newaliases touch -r /etc/aliases.db "$ALIASESDB_STAMP" else /usr/bin/newaliases fi } start() { [ "$EUID" != "0" ] & & exit 4 # Check that networking is up. [ ${NETWORKING} = "no" ] & & exit 1 conf_check # Start daemons. echo -n $"Starting postfix: " make_aliasesdb >/dev/null 2>& 1 [ -x $CHROOT_UPDATE ] & & $CHROOT_UPDATE /usr/sbin/postfix start 2>/dev/null 1>& 2 & & success || failure $"$prog start" RETVAL=$? 107 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide [ $RETVAL -eq 0 ] & & touch $lockfile echo return $RETVAL } The extensibility of the init script allowed specifying two custom functions, co nf_check() and make_al i asesd b(), that are called from the start() function block. On closer look, several external files and directories are mentioned in the above code: the main service executable /usr/sbi n/po stfi x, the /etc/po stfi x and /var/spo o l /po stfi x configuration directories, as well as the /usr/sbi n/po stco nf directory. Systemd supports only the predefined actions, but enables executing custom executables with ExecStart, ExecStartP re, ExecStartP o st, ExecSto p, and ExecR el o ad options. In case of po stfi x on Red Hat Enterprise Linux 7, the /usr/sbi n/po stfi x together with supporting scripts are executed on service start. Consult the po stfi x unit file at Example 8.15, “ postfix.service Unit File” . Converting complex init scripts requires understanding the purpose of every statement in the script. Some of the statements are specific to the operating system version, therefore you do not need to translate them. On the other hand, some adjustments might be needed in the new environment, both in unit file as well as in the service executable and supporting files. 8.6.4 . Modifying Exist ing Unit Files Services installed on the system come with default unit files that are stored in the /usr/l i b/systemd /system/ directory. System Administrators should not modify these files directly, therefore any customization must be confined to configuration files in the /etc/systemd /system/ directory. D epending on the extent of the required changes, pick one of the following approaches: Create a directory for supplementary configuration files at /etc/systemd /system/unit. d /. This method is recommended for most use cases. It enables extending the default configuration with additional functionality, while still referring to the original unit file. Changes to the default unit introduced with a package upgrade are therefore applied automatically. See Section 8.6.4, “ Extending the D efault Unit Configuration” for more information. Create a copy of the original unit file /usr/l i b/systemd /system/ in /etc/systemd /system/ and make changes there. The copy overrides the original file, therefore changes introduced with the package update are not applied. This method is useful for making significant unit changes that should persist regardless of package updates. See Section 8.6.4, “ Overriding the D efault Unit Configuration” for details. In order to return to the default configuration of the unit, just delete custom-created configuration files in /etc/systemd /system/. To apply changes to unit files without rebooting the system, execute: systemctl d aemo n-rel o ad The d aemo n-rel o ad option reloads all unit files and recreates the entire dependency tree, which is needed to immediately apply any change to a unit file. As an alternative, you can achieve the same result with the following command: i ni t q Also, if the modified unit file belongs to a running service, this service must be restarted to accept new settings: 108 Chapt er 8 . Managing Services wit h syst emd systemctl restart name. servi ce Ext e nding t he De fault Unit Co nfigurat io n To extend the default unit file with additional configuration options, first create a configuration directory in /etc/systemd /system/. If extending a service unit, execute the following command as ro o t: mkd i r /etc/systemd /system/name. servi ce. d Replace name with the name of the service you want to extend. The above syntax applies to all unit types. Create a configuration file in the directory made in the previous step. Note that the file name must end with the .conf suffix. Type: to uch /etc/systemd /system/name. servi ce. d /config_name. co nf Replace config_name with the name of the configuration file. This file adheres to the normal unit file structure, therefore all directives must be specified under appropriate sections, see Section 8.6.1, “ Understanding the Unit File Structure” . For example, to add a custom dependency, create a configuration file with the following content: [Unit] Requires=new_dependency After=new_dependency Where new_dependency stands for the unit to be marked as a dependency. Another example is a configuration file that restarts the service after its main process exited, with a delay of 30 seconds: [Service] Restart=always RestartSec=30 It is recommended to create small configuration files focused only on one task. Such files can be easily moved or linked to configuration directories of other services. To apply changes made to the unit, execute as ro o t: systemctl d aemo n-rel o ad systemctl restart name. servi ce Examp le 8.18. Ext en d in g t h e h t t p d .service C o n f ig u rat io n To modify the httpd.service unit so that a custom shell script is automatically executed when starting the Apache service, perform the following steps. First, create a directory and a custom configuration file: ~]# mkd i r /etc/systemd /system/httpd . servi ce. d ~]# to uch /etc/systemd /system/httpd . servi ce. d /custo m_scri pt. co nf 109 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Provided that the script you want to start automatically with Apache is located at /usr/l o cal /bi n/custo m. sh, insert the following text to the custo m_scri pt. co nf file: [Service] ExecStartPost=/usr/local/bin/custom.sh To apply the unit changes, execute: ~]# systemctl d aemo n-rel o ad ~]# systemctl restart httpd . servi ce Note The configuration files from configuration directories in /etc/systemd /system/ take precedence over unit files in /usr/l i b/systemd /system/. Therefore, if the configuration files contain an option that can be specified only once, such as D escri pti o n or ExecStart, the default value of this option is overridden. Note that in the output of the systemd -d el ta command, described in Section 8.6.4, “ Monitoring Overriden Units” , such units are always marked as [EXTEND ED ], even though in sum, certain options are actually overridden. Ove rriding t he De fault Unit Co nfigurat io n To make changes that will persist after updating the package that provides the unit file, first copy the file to the /etc/systemd /system/ directory. To do so, execute the following command as ro o t: cp /usr/l i b/systemd /system/name. servi ce /etc/systemd /system/name. servi ce Where name stands for the name of the service unit you wish to modify. The above syntax applies to all unit types. Open the copied file with a text editor, and make the desired changes. To apply the unit changes, execute as ro o t: systemctl d aemo n-rel o ad systemctl restart name. servi ce Mo nit o ring Ove rride n Unit s To display an overview of overridden or modified unit files, use the following command: systemd -d el ta For example, the output of the above command can look as follows: [EQ UIVALENT ] /etc/systemd/system/default.target → /usr/lib/systemd/system/default.target [O VER R ID D EN] /etc/systemd/system/autofs.service → /usr/lib/systemd/system/autofs.service --- /usr/lib/systemd/system/autofs.service 110 2014-10-16 Chapt er 8 . Managing Services wit h syst emd 21:30:39.000000000 -0400 +++ /etc/systemd/system/autofs.service 2014-11-21 10:00:58.513568275 0500 @ @ -8,7 +8,8 @ @ EnvironmentFile=-/etc/sysconfig/autofs ExecStart=/usr/sbin/automount $OPTIONS --pid-file /run/autofs.pid ExecReload=/usr/bin/kill -HUP $MAINPID -TimeoutSec=180 +TimeoutSec=240 +Restart=Always [Install] WantedBy=multi-user.target [MASKED ] /etc/systemd/system/cups.service → /usr/lib/systemd/system/cups.service [EXT END ED ] /usr/lib/systemd/system/sssd.service → /etc/systemd/system/sssd.service.d/journal.conf 4 overridden configuration files found. Table 8.13, “ systemd-delta D ifference Types” lists override types that can appear in the output of systemd -d el ta. Note that if a file is overridden, systemd -d el ta by default displays a summary of changes similar to the output of the d i ff command. T ab le 8.13. syst emd - d elt a D if f eren ce T yp es T yp e D escrip t io n [MASKED ] Masked unit files, see Section 8.2.7, “ D isabling a Service” for description of unit masking. Unmodified copies that override the original files but do not differ in content, typically symbolic links. Files that are redirected to another file. Overridden and changed files. Files that are extended with .conf files in the /etc/systemd /system/unit. d / directory. Unmodified files are displayed only when the --type= unchang ed option is used. [EQUIVALENT] [RED IRECTED ] [OVERRID EN] [EXTEND ED ] [UNCHANGED ] It is good practice to run systemd -d el ta after system update to check if there are any updates to the default units that are currently overridden by custom configuration. It is also possible to limit the output only to a certain difference type. For example, to view just the overridden units, execute: systemd -d el ta --type= o verri d d en 8.6.5. Working wit h Inst ant iat ed Unit s It is possible to instantiate multiple units from a single template configuration file at runtime. The " @" character is used to mark the template and to associate units with it. Instantiated units can be started from another unit file (using R eq ui res or Wants options), or with the systemctl start command. Instantiated service units are named the following way: template_name@ instance_name.service 111 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Where template_name stands for the name of the template configuration file. Replace instance_name with the name for the unit instance. Several instances can point to the same template file with configuration options common for all instances of the unit. Template unit name has the form of: unit_name@ .service For example, the following Wants setting in a unit file: Wants=getty@ ttyA.service,getty@ ttyB.service first makes systemd search for given service units. If no such units are found, the part between " @" and the type suffix is ignored and systemd searches for the g etty@ . servi ce file, reads the configuration from it, and starts the services. Wildcard characters, called unit specifiers, can be used in any unit configuration file. Unit specifiers substitute certain unit parameters and are interpreted at runtime. Table 8.14, “ Important Unit Specifiers” lists unit specifiers that are particularly useful for template units. T ab le 8.14 . Imp o rt an t U n it Sp ecif iers U n it Sp ecif ier Mean in g %n Full unit name %p Prefix name %i Instance name %H Host name %t Runtime directory D escrip t io n Stands for the full unit name including the type suffix. %N has the same meaning but also replaces the forbidden characters for ASCII codes. Stands for a unit name with type suffix removed. For instantiated units % p stands for the part of the unit name before the " @" character. Is the part of the instantiated unit name between the " @" character and the type suffix. %I has the same meaning but also replaces the forbidden characters for ASCII codes. Stands for the hostname of the running system at the point in time the unit configuration is loaded. Represents the runtime directory, which is either /run for the ro o t user, or the value of the XD G_RUNTIME_D IR variable for unprivileged users. For a complete list of unit specifiers, see the systemd . uni t(5) manual page. For example, the g etty@ . servi ce template contains the following directives: [Unit] Description=Getty on %I ... [Service] ExecStart=-/sbin/agetty --noclear %I $TERM ... When the getty@ttyA.service and getty@ttyB.service are instantiated form the above template, D escri pti o n= is resolved as Getty on ttyA and Getty on ttyB. 8.7. Addit ional Resources 112 Chapt er 8 . Managing Services wit h syst emd For more information on systemd and its usage on Red Hat Enterprise Linux 7, see the resources listed below. Inst alled Document at ion systemctl (1) — The manual page for the systemctl command line utility provides a complete list of supported options and commands. systemd (1) — The manual page for the systemd system and service manager provides more information about its concepts and documents available command line options and environment variables, supported configuration files and directories, recognized signals, and available kernel options. systemd -d el ta(1) — The manual page for the systemd -d el ta utility that allows to find extended and overridden configuration files. systemd . uni t(5) — The manual page named systemd . uni t provides in-depth information about systemd unit files and documents all available configuration options. systemd . servi ce(5) — The manual page named systemd . servi ce documents the format of service unit files. systemd . targ et(5) — The manual page named systemd . targ et documents the format of target unit files. systemd . ki l l (5) — The manual page named systemd . ki l l documents the configuration of the process killing procedure. Online Document at ion Red Hat Enterprise Linux 7 Networking Guide — The Networking Guide for Red Hat Enterprise Linux 7 documents relevant information regarding the configuration and administration of network interfaces, networks, and network services in this system. It provides an introduction to the ho stnamectl utility, explains how to use it to view and set host names on the command line, both locally and remotely, and provides important information about the selection of host names and domain names. Red Hat Enterprise Linux 7 D esktop Migration and Administration Guide — The Desktop Migration and Administration Guide for Red Hat Enterprise Linux 7 documents the migration planning, deployment, configuration, and administration of the GNOME 3 desktop on this system. It introduces the l o g i nd service, enumerates its most significant features, and explains how to use the l o g i nctl utility to list active sessions and enable multi-seat support. Red Hat Enterprise Linux 7 SELinux User's and Administrator's Guide — The SELinux User's and Administrator's Guide for Red Hat Enterprise Linux 7 describes the basic principles of SELinux and documents in detail how to configure and use SELinux with various services such as the Apache HTTP Server, Postfix, PostgreSQL, or OpenShift. It explains how to configure SELinux access permissions for system services managed by systemd. Red Hat Enterprise Linux 7 Installation Guide — The Installation Guide for Red Hat Enterprise Linux 7 documents how to install the system on AMD 64 and Intel 64 systems, 64-bit IBM Power Systems servers, and IBM System z. It also covers advanced installation methods such as Kickstart installations, PXE installations, and installations over the VNC protocol. In addition, it describes common post-installation tasks and explains how to troubleshoot installation problems, including detailed instructions on how to boot into rescue mode or recover the root password. Red Hat Enterprise Linux 7 Security Guide — The Security Guide for Red Hat Enterprise Linux 7 113 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide assists users and administrators in learning the processes and practices of securing their workstations and servers against local and remote intrusion, exploitation, and malicious activity. It also explains how to secure critical system services. systemd Home Page — The project home page provides more information about systemd. See Also Chapter 1, System Locale and Keyboard Configuration documents how to manage the system locale and keyboard layouts. It explains how to use the l o cal ectl utility to view the current locale, list available locales, and set the system locale on the command line, as well as to view the current keyboard layout, list available keymaps, and enable a particular keyboard layout on the command line. Chapter 2, Configuring the Date and Time documents how to manage the system date and time. It explains the difference between a real-time clock and system clock and describes how to use the ti med atectl utility to display the current settings of the system clock, configure the date and time, change the time zone, and synchronize the system clock with a remote server. Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. Chapter 9, OpenSSH describes how to configure an SSH server and how to use the ssh, scp, and sftp client utilities to access it. Chapter 20, Viewing and Managing Log Files provides an introduction to journald. It describes the journal, introduces the jo urnal d service, and documents how to use the jo urnal ctl utility to view log entries, enter live view mode, and filter log entries. In addition, this chapter describes how to give non-root users access to system logs and enable persistent storage for log files. 114 Chapt er 9 . O penSSH Chapter 9. OpenSSH SSH (Secure Shell) is a protocol which facilitates secure communications between two systems using a client-server architecture and allows users to log in to server host systems remotely. Unlike other remote communication protocols, such as FT P or T el net, SSH encrypts the login session, rendering the connection difficult for intruders to collect unencrypted passwords. The ssh program is designed to replace older, less secure terminal applications used to log in to remote hosts, such as tel net or rsh. A related program called scp replaces older programs designed to copy files between hosts, such as rcp. Because these older applications do not encrypt passwords transmitted between the client and the server, avoid them whenever possible. Using secure methods to log in to remote systems decreases the risks for both the client system and the remote host. Red Hat Enterprise Linux includes the general OpenSSH package, openssh, as well as the OpenSSH server, openssh-server, and client, openssh-clients, packages. Note, the OpenSSH packages require the OpenSSL package openssl-libs, which installs several important cryptographic libraries, enabling OpenSSH to provide encrypted communications. 9.1. T he SSH Prot ocol 9.1.1. Why Use SSH? Potential intruders have a variety of tools at their disposal enabling them to disrupt, intercept, and reroute network traffic in an effort to gain access to a system. In general terms, these threats can be categorized as follows: In t ercep t io n o f co mmu n icat io n b et ween t wo syst ems The attacker can be somewhere on the network between the communicating parties, copying any information passed between them. He may intercept and keep the information, or alter the information and send it on to the intended recipient. This attack is usually performed using a packet sniffer, a rather common network utility that captures each packet flowing through the network, and analyzes its content. Imp erso n at io n o f a p art icu lar h o st Attacker's system is configured to pose as the intended recipient of a transmission. If this strategy works, the user's system remains unaware that it is communicating with the wrong host. This attack can be performed using a technique known as DNS poisoning, or via so-called IP spoofing. In the first case, the intruder uses a cracked D NS server to point client systems to a maliciously duplicated host. In the second case, the intruder sends falsified network packets that appear to be from a trusted host. Both techniques intercept potentially sensitive information and, if the interception is made for hostile reasons, the results can be disastrous. If SSH is used for remote shell login and file copying, these security threats can be greatly diminished. This is because the SSH client and server use digital signatures to verify their identity. Additionally, all communication between the client and server systems is encrypted. Attempts to spoof the identity of either side of a communication does not work, since each packet is encrypted using a key known only by the local and remote systems. 9.1.2. Main Feat ures 115 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The SSH protocol provides the following safeguards: N o o n e can p o se as t h e in t en d ed server After an initial connection, the client can verify that it is connecting to the same server it had connected to previously. N o o n e can cap t u re t h e au t h en t icat io n in f o rmat io n The client transmits its authentication information to the server using strong, 128-bit encryption. N o o n e can in t ercep t t h e co mmu n icat io n All data sent and received during a session is transferred using 128-bit encryption, making intercepted transmissions extremely difficult to decrypt and read. Additionally, it also offers the following options: It p ro vid es secu re mean s t o u se g rap h ical ap p licat io n s o ver a n et wo rk Using a technique called X11 forwarding, the client can forward X11 (X Window System) applications from the server. It p ro vid es a way t o secu re o t h erwise in secu re p ro t o co ls The SSH protocol encrypts everything it sends and receives. Using a technique called port forwarding, an SSH server can become a conduit to securing otherwise insecure protocols, like POP, and increasing overall system and data security. It can b e u sed t o creat e a secu re ch an n el The OpenSSH server and client can be configured to create a tunnel similar to a virtual private network for traffic between server and client machines. It su p p o rt s t h e K erb ero s au t h en t icat io n OpenSSH servers and clients can be configured to authenticate using the GSSAPI (Generic Security Services Application Program Interface) implementation of the Kerberos network authentication protocol. 9.1.3. Prot ocol Versions Two varieties of SSH currently exist: version 1, and newer version 2. The OpenSSH suite under Red Hat Enterprise Linux uses SSH version 2, which has an enhanced key exchange algorithm not vulnerable to the known exploit in version 1. However, for compatibility reasons, the OpenSSH suite does support version 1 connections as well. Important To ensure maximum security for your connection, it is recommended that only SSH version 2compatible servers and clients are used whenever possible. 9.1.4 . Event Sequence of an SSH Connect ion The following series of events help protect the integrity of SSH communication between two hosts. 116 Chapt er 9 . O penSSH 1. A cryptographic handshake is made so that the client can verify that it is communicating with the correct server. 2. The transport layer of the connection between the client and remote host is encrypted using a symmetric cipher. 3. The client authenticates itself to the server. 4. The remote client interacts with the remote host over the encrypted connection. 9 .1 .4 .1 . T ranspo rt Laye r The primary role of the transport layer is to facilitate safe and secure communication between the two hosts at the time of authentication and during subsequent communication. The transport layer accomplishes this by handling the encryption and decryption of data, and by providing integrity protection of data packets as they are sent and received. The transport layer also provides compression, speeding the transfer of information. Once an SSH client contacts a server, key information is exchanged so that the two systems can correctly construct the transport layer. The following steps occur during this exchange: Keys are exchanged The public key encryption algorithm is determined The symmetric encryption algorithm is determined The message authentication algorithm is determined The hash algorithm is determined D uring the key exchange, the server identifies itself to the client with a unique host key. If the client has never communicated with this particular server before, the server's host key is unknown to the client and it does not connect. OpenSSH gets around this problem by accepting the server's host key. This is done after the user is notified and has both accepted and verified the new host key. In subsequent connections, the server's host key is checked against the saved version on the client, providing confidence that the client is indeed communicating with the intended server. If, in the future, the host key no longer matches, the user must remove the client's saved version before a connection can occur. Warning It is possible for an attacker to masquerade as an SSH server during the initial contact since the local system does not know the difference between the intended server and a false one set up by an attacker. To help prevent this, verify the integrity of a new SSH server by contacting the server administrator before connecting for the first time or in the event of a host key mismatch. SSH is designed to work with almost any kind of public key algorithm or encoding format. After an initial key exchange creates a hash value used for exchanges and a shared secret value, the two systems immediately begin calculating new keys and algorithms to protect authentication and future data sent over the connection. 117 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide After a certain amount of data has been transmitted using a given key and algorithm (the exact amount depends on the SSH implementation), another key exchange occurs, generating another set of hash values and a new shared secret value. Even if an attacker is able to determine the hash and shared secret value, this information is only useful for a limited period of time. 9 .1 .4 .2 . Aut he nt icat io n Once the transport layer has constructed a secure tunnel to pass information between the two systems, the server tells the client the different authentication methods supported, such as using a private key-encoded signature or typing a password. The client then tries to authenticate itself to the server using one of these supported methods. SSH servers and clients can be configured to allow different types of authentication, which gives each side the optimal amount of control. The server can decide which encryption methods it supports based on its security model, and the client can choose the order of authentication methods to attempt from the available options. 9 .1 .4 .3. Channe ls After a successful authentication over the SSH transport layer, multiple channels are opened via a technique called multiplexing [1] . Each of these channels handles communication for different terminal sessions and for forwarded X11 sessions. Both clients and servers can create a new channel. Each channel is then assigned a different number on each end of the connection. When the client attempts to open a new channel, the clients sends the channel number along with the request. This information is stored by the server and is used to direct communication to that channel. This is done so that different types of sessions do not affect one another and so that when a given session ends, its channel can be closed without disrupting the primary SSH connection. Channels also support flow-control, which allows them to send and receive data in an orderly fashion. In this way, data is not sent over the channel until the client receives a message that the channel is open. The client and server negotiate the characteristics of each channel automatically, depending on the type of service the client requests and the way the user is connected to the network. This allows great flexibility in handling different types of remote connections without having to change the basic infrastructure of the protocol. 9.2. Configuring OpenSSH 9.2.1. Configurat ion Files There are two different sets of configuration files: those for client programs (that is, ssh, scp, and sftp), and those for the server (the sshd daemon). System-wide SSH configuration information is stored in the /etc/ssh/ directory as described in Table 9.1, “ System-wide configuration files” . User-specific SSH configuration information is stored in ~ /. ssh/ within the user's home directory as described in Table 9.2, “ User-specific configuration files” . T ab le 9 .1. Syst em- wid e co n f ig u rat io n f iles File 118 D escrip t io n Chapt er 9 . O penSSH File D escrip t io n Contains D iffie-Hellman groups used for the D iffie-Hellman key exchange which is critical for constructing a secure transport layer. When keys are exchanged at the beginning of an SSH session, a shared, secret value is created which cannot be determined by either party alone. This value is then used to provide host authentication. /etc/ssh/ssh_co nfi g The default SSH client configuration file. Note that it is overridden by ~ /. ssh/co nfi g if it exists. /etc/ssh/sshd _co nfi g The configuration file for the sshd daemon. /etc/ssh/ssh_ho st_ecd sa_key The ECD SA private key used by the sshd daemon. /etc/ssh/ssh_ho st_ecd sa_key The ECD SA public key used by the sshd daemon. . pub /etc/ssh/ssh_ho st_key The RSA private key used by the sshd daemon for version 1 of the SSH protocol. /etc/ssh/ssh_ho st_key. pub The RSA public key used by the sshd daemon for version 1 of the SSH protocol. /etc/ssh/ssh_ho st_rsa_key The RSA private key used by the sshd daemon for version 2 of the SSH protocol. /etc/ssh/ssh_ho st_rsa_key. p The RSA public key used by the sshd daemon for version 2 ub of the SSH protocol. /etc/pam. d /sshd The PAM configuration file for the sshd daemon. /etc/sysco nfi g /sshd Configuration file for the sshd service. /etc/ssh/mo d ul i T ab le 9 .2. U ser- sp ecif ic co n f ig u rat io n f iles File D escrip t io n ~ /. ssh/autho ri zed _keys Holds a list of authorized public keys for servers. When the client connects to a server, the server authenticates the client by checking its signed public key stored within this file. Contains the ECD SA private key of the user. The ECD SA public key of the user. The RSA private key used by ssh for version 2 of the SSH protocol. The RSA public key used by ssh for version 2 of the SSH protocol. The RSA private key used by ssh for version 1 of the SSH protocol. The RSA public key used by ssh for version 1 of the SSH protocol. Contains host keys of SSH servers accessed by the user. This file is very important for ensuring that the SSH client is connecting to the correct SSH server. ~ /. ssh/i d _ecd sa ~ /. ssh/i d _ecd sa. pub ~ /. ssh/i d _rsa ~ /. ssh/i d _rsa. pub ~ /. ssh/i d enti ty ~ /. ssh/i d enti ty. pub ~ /. ssh/kno wn_ho sts For information concerning various directives that can be used in the SSH configuration files, see the ssh_co nfi g (5) and sshd _co nfi g (5) manual pages. 9.2.2. St art ing an OpenSSH Server In order to run an OpenSSH server, you must have the openssh-server package installed (see Section 7.2.4, “ Installing Packages” for more information on how to install new packages in Red Hat Enterprise Linux 7). 119 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To start the sshd daemon in the current session, type the following at a shell prompt as ro o t: ~]# systemctl start sshd . servi ce To stop the running sshd daemon in the current session, use the following command as ro o t: ~]# systemctl sto p sshd . servi ce If you want the daemon to start automatically at the boot time, type as ro o t: ~]# systemctl enabl e sshd . servi ce ln -s '/usr/lib/systemd/system/sshd.service' '/etc/systemd/system/multiuser.target.wants/sshd.service' For more information on how to manage system services in Red Hat Enterprise Linux, see Chapter 8, Managing Services with systemd. Note that if you reinstall the system, a new set of identification keys will be created. As a result, clients who had connected to the system with any of the OpenSSH tools before the reinstall will see the following message: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that the RSA host key has just been changed. To prevent this, you can backup the relevant files from the /etc/ssh/ directory (see Table 9.1, “ System-wide configuration files” for a complete list), and restore them whenever you reinstall the system. 9.2.3. Requiring SSH for Remot e Connect ions For SSH to be truly effective, using insecure connection protocols should be prohibited. Otherwise, a user's password may be protected using SSH for one session, only to be captured later while logging in using Telnet. Some services to disable include tel net, rsh, rl o g i n, and vsftpd . For information on how to configure the vsftpd service, see Section 14.2, “ FTP” . To learn how to manage system services in Red Hat Enterprise Linux 7, read Chapter 8, Managing Services with systemd. 9.2.4 . Using Key-based Aut hent icat ion To improve the system security even further, generate SSH key pairs and then enforce key-based authentication by disabling password authentication. To do so, open the /etc/ssh/sshd _co nfi g configuration file in a text editor such as vi or n an o , and change the P asswo rd Authenti cati o n option as follows: PasswordAuthentication no 120 Chapt er 9 . O penSSH If you are working on a system other than a new default installation, check that P ubkeyAuthenti cati o n no has n o t been set. If connected remotely, not using console or out-ofband access, testing the key-based log in process before disabling password authentication is advised. To be able to use ssh, scp, or sftp to connect to the server from a client machine, generate an authorization key pair by following the steps below. Note that keys must be generated for each user separately. Red Hat Enterprise Linux 7 uses SSH Protocol 2 and RSA keys by default (see Section 9.1.3, “ Protocol Versions” for more information). Important If you complete the steps as ro o t, only ro o t will be able to use the keys. Note If you reinstall your system and want to keep previously generated key pairs, backup the ~ /. ssh/ directory. After reinstalling, copy it back to your home directory. This process can be done for all users on your system, including ro o t. 9 .2 .4 .1 . Ge ne rat ing Ke y Pairs To generate an RSA key pair for version 2 of the SSH protocol, follow these steps: 1. Generate an RSA key pair by typing the following at a shell prompt: ~]$ ssh-keyg en -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/USER/.ssh/id_rsa): 2. Press Enter to confirm the default location, ~ /. ssh/i d _rsa, for the newly created key. 3. Enter a passphrase, and confirm it by entering it again when prompted to do so. For security reasons, avoid using the same password as you use to log in to your account. After this, you will be presented with a message similar to this: Your identification has been saved in /home/USER/.ssh/id_rsa. Your public key has been saved in /home/USER/.ssh/id_rsa.pub. The key fingerprint is: e7:97:c7:e2:0e:f9:0e:fc:c4:d7:cb:e5:31:11:92:14 USER@ penguin.example.com The key's randomart image is: +--[ RSA 2048]----+ | E. | | . . | | o . | | . .| | S . . | | + o o ..| 121 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide | * * +oo| | O +..=| | o* o.| +-----------------+ 4. By default, the permissions of the ~ /. ssh/ directory are set to rwx------ or 70 0 expressed in octal notation. This is to ensure that only the USER can view the contents. If required, this can be confirmed with the following command: ~]$ l s -l d ~ /. ssh ~]$ ls -ld ~/.ssh/ drwx------. 2 USER USER 54 Nov 25 16:56 /home/USER/.ssh/ 5. To copy the public key to a remote machine, issue a command in the following format: ssh-co py-i d user@hostname This will copy the most recently modified ~ /. ssh/i d *. pub public key if it is not yet installed. Alternatively, specify the public keys file name as follows: ssh-co py-i d -i ~ /. ssh/i d _rsa. pub user@hostname This will copy the content of ~ /. ssh/i d _rsa. pub into the ~ /. ssh/autho ri zed _keys file on the machine to which you want to connect. If the file already exists, the keys are appended to its end. To generate an ECD SA key pair for version 2 of the SSH protocol, follow these steps: 1. Generate an ECD SA key pair by typing the following at a shell prompt: ~]$ ssh-keyg en -t ecd sa Generating public/private ecdsa key pair. Enter file in which to save the key (/home/USER/.ssh/id_ecdsa): 2. Press Enter to confirm the default location, ~ /. ssh/i d _ecd sa, for the newly created key. 3. Enter a passphrase, and confirm it by entering it again when prompted to do so. For security reasons, avoid using the same password as you use to log in to your account. After this, you will be presented with a message similar to this: Your identification has been saved in /home/USER/.ssh/id_ecdsa. Your public key has been saved in /home/USER/.ssh/id_ecdsa.pub. The key fingerprint is: fd:1d:ca:10:52:96:21:43:7e:bd:4c:fc:5b:35:6b:63 USER@ penguin.example.com The key's randomart image is: +--[ECDSA 256]---+ | .+ +o | | . =.o | | o o + ..| | + + o +| | S o o oE.| | + oo+.| 122 Chapt er 9 . O penSSH | + o | | | | | +-----------------+ 4. By default, the permissions of the ~ /. ssh/ directory are set to rwx------ or 70 0 expressed in octal notation. This is to ensure that only the USER can view the contents. If required, this can be confirmed with the following command: ~]$ l s -l d ~ /. ssh ~]$ ls -ld ~/.ssh/ drwx------. 2 USER USER 54 Nov 25 16:56 /home/USER/.ssh/ 5. To copy the public key to a remote machine, issue a command in the following format: ssh-co py-i d USER@hostname This will copy the most recently modified ~ /. ssh/i d *. pub public key if it is not yet installed. Alternatively, specify the public keys file name as follows: ssh-co py-i d -i ~ /. ssh/i d _ecd sa. pub USER@hostname This will copy the content of ~ /. ssh/i d _ecd sa. pub into the ~ /. ssh/autho ri zed _keys on the machine to which you want to connect. If the file already exists, the keys are appended to its end. See Section 9.2.4.2, “ Configuring ssh-agent” for information on how to set up your system to remember the passphrase. Important The private key is for your personal use only, and it is important that you never give it to anyone. 9 .2 .4 .2 . Co nfiguring ssh-age nt To store your passphrase so that you do not have to enter it each time you initiate a connection with a remote machine, you can use the ssh-ag ent authentication agent. If you are running GNOME, you can configure it to prompt you for your passphrase whenever you log in and remember it during the whole session. Otherwise you can store the passphrase for a certain shell prompt. To save your passphrase during your GNOME session, follow these steps: 1. Make sure you have the openssh-askpass package installed. If not, see Section 7.2.4, “ Installing Packages” for more information on how to install new packages in Red Hat Enterprise Linux. 2. Press the Super key to enter the Activities Overview, type Startup Appl i cati o ns and then press Enter. The St art u p Ap p licat io n s Pref eren ces tool appears. The tab containing a list of available startup programs will be shown by default. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. 123 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 9 .1. St art u p Ap p licat io n s Pref eren ces 3. Click the Ad d button on the right, and enter /usr/bi n/ssh-ad d in the C o mmand field. Fig u re 9 .2. Ad d in g n ew ap p licat io n 4. Click Ad d and make sure the checkbox next to the newly added item is selected. 124 Chapt er 9 . O penSSH Fig u re 9 .3. En ab lin g t h e ap p licat io n 5. Log out and then log back in. A dialog box will appear prompting you for your passphrase. From this point on, you should not be prompted for a password by ssh, scp, or sftp. Fig u re 9 .4 . En t erin g a p assp h rase To save your passphrase for a certain shell prompt, use the following command: ~]$ ssh-ad d Enter passphrase for /home/USER/.ssh/id_rsa: Note that when you log out, your passphrase will be forgotten. You must execute the command each time you log in to a virtual console or a terminal window. 125 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 9.3. OpenSSH Client s To connect to an OpenSSH server from a client machine, you must have the openssh-clients package installed (see Section 7.2.4, “ Installing Packages” for more information on how to install new packages in Red Hat Enterprise Linux). 9.3.1. Using t he ssh Ut ilit y The ssh utility allows you to log in to a remote machine and execute commands there. It is a secure replacement for the rl o g i n, rsh, and tel net programs. Similarly to the tel net command, log in to a remote machine by using the following command: ssh hostname For example, to log in to a remote machine named peng ui n. exampl e. co m, type the following at a shell prompt: ~]$ ssh peng ui n. exampl e. co m This will log you in with the same user name you are using on the local machine. If you want to specify a different user name, use a command in the following form: ssh username@ hostname For example, to log in to peng ui n. exampl e. co m as USER , type: ~]$ ssh USER @ peng ui n. exampl e. co m The first time you initiate a connection, you will be presented with a message similar to this: The authenticity of host 'penguin.example.com' can't be established. ECDSA key fingerprint is 256 da:24:43:0b:2e:c1:3f:a1:84:13:92:01:52:b4:84:ff. Are you sure you want to continue connecting (yes/no)? Users should always check if the fingerprint is correct before answering the question in this dialog. The user can ask the administrator of the server to confirm the key is correct. This should be done in a secure and previously agreed way. If the user has access to the server's host keys, the fingerprint can be checked by using the ssh-keyg en command as follows: ~]# ssh-keyg en -l -f /etc/ssh/ssh_ho st_ecd sa_key. pub 256 da:24:43:0b:2e:c1:3f:a1:84:13:92:01:52:b4:84:ff (ECDSA) Type yes to accept the key and confirm the connection. You will see a notice that the server has been added to the list of known hosts, and a prompt asking for your password: Warning: Permanently added 'penguin.example.com' (ECDSA) to the list of known hosts. USER@ penguin.example.com's password: 126 Chapt er 9 . O penSSH Important If the SSH server's host key changes, the client notifies the user that the connection cannot proceed until the server's host key is deleted from the ~ /. ssh/kno wn_ho sts file. Before doing this, however, contact the system administrator of the SSH server to verify the server is not compromised. To remove a key from the ~ /. ssh/kno wn_ho sts file, issue a command as follows: ~]# ssh-keyg en -R penguin.example.com # Host penguin.example.com found: line 15 type ECDSA /home/USER/.ssh/known_hosts updated. Original contents retained as /home/USER/.ssh/known_hosts.old After entering the password, you will be provided with a shell prompt for the remote machine. Alternatively, the ssh program can be used to execute a command on the remote machine without logging in to a shell prompt: ssh [username@ ]hostname command For example, the /etc/red hat-rel ease file provides information about the Red Hat Enterprise Linux version. To view the contents of this file on peng ui n. exampl e. co m, type: ~]$ ssh USER @ peng ui n. exampl e. co m cat /etc/red hat-rel ease USER@ penguin.example.com's password: Red Hat Enterprise Linux Server release 7.0 (Maipo) After you enter the correct password, the user name will be displayed, and you will return to your local shell prompt. 9.3.2. Using t he scp Ut ilit y scp can be used to transfer files between machines over a secure, encrypted connection. In its design, it is very similar to rcp. To transfer a local file to a remote system, use a command in the following form: scp localfile username@ hostname: remotefile For example, if you want to transfer tag l i st. vi m to a remote machine named peng ui n. exampl e. co m, type the following at a shell prompt: ~]$ scp tag l i st. vi m USER @ peng ui n. exampl e. co m: . vi m/pl ug i n/tag l i st. vi m USER@ penguin.example.com's password: taglist.vim 100% 144KB 144.5KB/s 00:00 Multiple files can be specified at once. To transfer the contents of . vi m/pl ug i n/ to the same directory on the remote machine peng ui n. exampl e. co m, type the following command: 127 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]$ scp . vi m/pl ug i n/* USER @ peng ui n. exampl e. co m: . vi m/pl ug i n/ USER@ penguin.example.com's password: closetag.vim 100% 13KB 12.6KB/s 00:00 snippetsEmu.vim 100% 33KB 33.1KB/s 00:00 taglist.vim 100% 144KB 144.5KB/s 00:00 To transfer a remote file to the local system, use the following syntax: scp username@ hostname: remotefile localfile For instance, to download the . vi mrc configuration file from the remote machine, type: ~]$ scp USER @ peng ui n. exampl e. co m: . vi mrc . vi mrc USER@ penguin.example.com's password: .vimrc 100% 2233 00:00 2.2KB/s 9.3.3. Using t he sftp Ut ilit y The sftp utility can be used to open a secure, interactive FTP session. In its design, it is similar to ftp except that it uses a secure, encrypted connection. To connect to a remote system, use a command in the following form: sftp username@ hostname For example, to log in to a remote machine named peng ui n. exampl e. co m with USER as a user name, type: ~]$ sftp USER @ peng ui n. exampl e. co m USER@ penguin.example.com's password: Connected to penguin.example.com. sftp> After you enter the correct password, you will be presented with a prompt. The sftp utility accepts a set of commands similar to those used by ftp (see Table 9.3, “ A selection of available sftp commands” ). T ab le 9 .3. A select io n o f availab le sf t p co mman d s C o mman d D escrip t io n l s [directory] List the content of a remote directory. If none is supplied, a current working directory is used by default. Change the remote working directory to directory. Create a remote directory. Remove a remote directory. Transfer localfile to a remote machine. Transfer remotefile from a remote machine. cd directory mkd i r directory rmd i r path put localfile [remotefile] g et remotefile [localfile] 128 Chapt er 9 . O penSSH For a complete list of available commands, see the sftp(1) manual page. 9.4 . More T han a Secure Shell A secure command line interface is just the beginning of the many ways SSH can be used. Given the proper amount of bandwidth, X11 sessions can be directed over an SSH channel. Or, by using TCP/IP forwarding, previously insecure port connections between systems can be mapped to specific SSH channels. 9.4 .1. X11 Forwarding To open an X11 session over an SSH connection, use a command in the following form: ssh -Y username@ hostname For example, to log in to a remote machine named peng ui n. exampl e. co m with USER as a user name, type: ~]$ ssh -Y USER @ peng ui n. exampl e. co m USER@ penguin.example.com's password: When an X program is run from the secure shell prompt, the SSH client and server create a new secure channel, and the X program data is sent over that channel to the client machine transparently. X11 forwarding can be very useful. For example, X11 forwarding can be used to create a secure, interactive session of the Prin t Set t in g s utility. To do this, connect to the server using ssh and type: ~]$ system-co nfi g -pri nter & The Prin t Set t in g s tool will appear, allowing the remote user to safely configure printing on the remote system. 9.4 .2. Port Forwarding SSH can secure otherwise insecure T C P /IP protocols via port forwarding. When using this technique, the SSH server becomes an encrypted conduit to the SSH client. Port forwarding works by mapping a local port on the client to a remote port on the server. SSH can map any port from the server to any port on the client. Port numbers do not need to match for this technique to work. Note Setting up port forwarding to listen on ports below 1024 requires ro o t level access. To create a TCP/IP port forwarding channel which listens for connections on the l o cal ho st, use a command in the following form: ssh -L local-port: remote-hostname: remote-port username@ hostname 129 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide For example, to check email on a server called mai l . exampl e. co m using P O P 3 through an encrypted connection, use the following command: ~]$ ssh -L 110 0 : mai l . exampl e. co m: 110 mai l . exampl e. co m Once the port forwarding channel is in place between the client machine and the mail server, direct a POP3 mail client to use port 110 0 on the l o cal ho st to check for new email. Any requests sent to port 110 0 on the client system will be directed securely to the mai l . exampl e. co m server. If mai l . exampl e. co m is not running an SSH server, but another machine on the same network is, SSH can still be used to secure part of the connection. However, a slightly different command is necessary: ~]$ ssh -L 110 0 : mai l . exampl e. co m: 110 o ther. exampl e. co m In this example, POP3 requests from port 110 0 on the client machine are forwarded through the SSH connection on port 22 to the SSH server, o ther. exampl e. co m. Then, o ther. exampl e. co m connects to port 110 on mai l . exampl e. co m to check for new email. Note that when using this technique, only the connection between the client system and o ther. exampl e. co m SSH server is secure. Port forwarding can also be used to get information securely through network firewalls. If the firewall is configured to allow SSH traffic via its standard port (that is, port 22) but blocks access to other ports, a connection between two hosts using the blocked ports is still possible by redirecting their communication over an established SSH connection. Important Using port forwarding to forward connections in this manner allows any user on the client system to connect to that service. If the client system becomes compromised, the attacker also has access to forwarded services. System administrators concerned about port forwarding can disable this functionality on the server by specifying a No parameter for the Al l o wT cpFo rward i ng line in /etc/ssh/sshd _co nfi g and restarting the sshd service. 9.5. Addit ional Resources For more information on how to configure or connect to an OpenSSH server on Red Hat Enterprise Linux, see the resources listed below. Inst alled Document at ion sshd (8) — The manual page for the sshd daemon documents available command line options and provides a complete list of supported configuration files and directories. ssh(1) — The manual page for the ssh client application provides a complete list of available command line options and supported configuration files and directories. scp(1) — The manual page for the scp utility provides a more detailed description of this utility and its usage. 130 Chapt er 9 . O penSSH sftp(1) — The manual page for the sftp utility. ssh-keyg en(1) — The manual page for the ssh-keyg en utility documents in detail how to use it to generate, manage, and convert authentication keys used by ssh. ssh_co nfi g (5) — The manual page named ssh_co nfi g documents available SSH client configuration options. sshd _co nfi g (5) — The manual page named sshd _co nfi g provides a full description of available SSH daemon configuration options. Online Document at ion OpenSSH Home Page — The OpenSSH home page containing further documentation, frequently asked questions, links to the mailing lists, bug reports, and other useful resources. OpenSSL Home Page — The OpenSSL home page containing further documentation, frequently asked questions, links to the mailing lists, and other useful resources. See Also Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. Chapter 8, Managing Services with systemd provides more information on systemd and documents how to use the systemctl command to manage system services. [1] A multip lexed c o nnec tio n c o ns is ts o f s everal s ig nals b eing s ent o ver a s hared , c o mmo n med ium. With SSH, d ifferent c hannels are s ent o ver a c o mmo n s ec ure c o nnec tio n. 131 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 10. TigerVNC T i g erVNC (Tiger Virtual Network Computing) is a system for graphical desktop sharing which allows you to remotely control other computers. T i g erVNC works on the client-server principle: a server shares its output (vncserver) and a clien t (vncvi ewer) connects to the server. Note Unlike in previous Red Hat Enterprise Linux distributions, T i g erVNC in Red Hat Enterprise Linux 7 uses the systemd system management daemon for its configuration. The /etc/sysco nfi g /vncserver configuration file has been replaced by /etc/systemd /system/vncserver@ . servi ce. 10.1. VNC Server vncserver is a utility which starts a VNC (Virtual Network Computing) desktop. It runs Xvn c with appropriate options and starts a window manager on the VNC desktop. vncserver allows users to run separate sessions in parallel on a machine which can then be accessed by any number of clients from anywhere. 10.1.1. Inst alling VNC Server To install the T ig erVN C server, issue the following command as ro o t: ~]# yum i nstal l ti g ervnc-server 10.1.2. Configuring VNC Server The VNC server can be configured to start a display for one or more users, provided that accounts for the users exist on the system, with optional parameters such as for display settings, network address and port, and security settings. Pro ced u re 10.1. C o n f ig u rin g a VN C D isp lay f o r a Sin g le U ser 1. A configuration file named /etc/systemd /system/vncserver@ . servi ce is required. To create this file, copy the /l i b/systemd /system/vncserver@ . servi ce file as ro o t: ~ ]# cp /l i b/systemd /system/vncserver@ . servi ce /etc/systemd /system/vncserver@ . servi ce There is no need to include the display number in the file name because systemd automatically creates the appropriately named instance in memory on demand, replacing ' %i ' in the service file by the display number. For a single user it is not necessary to rename the file. For multiple users, a uniquely named service file for each user is required, for example, by adding the user name to the file name in some way. See Section 10.1.2.1, “ Configuring VNC Server for Two Users” for details. 132 Chapt er 1 0 . T igerVNC 2. Edit /etc/systemd /system/vncserver@ . servi ce, replacing USER with the actual user name. Leave the remaining lines of the file unmodified. The -g eo metry argument specifies the size of the VNC desktop to be created; by default, it is set to 10 24 x76 8. ExecStart=/sbin/runuser -l USER -c "/usr/bin/vncserver %i -geometry 1280x1024" PIDFile=/home/USER/.vnc/%H%i.pid 3. Save the changes. 4. To make the changes take effect immediately, issue the following command: ~ ]# systemctl d aemo n-rel o ad 5. Set the password for the user or users defined in the configuration file. Note that you need to switch from ro o t to USER first. ~ ]# su - USER ~ ]$ vncpasswd Password: Verify: Important The stored password is not encrypted; anyone who has access to the password file can find the plain-text password. Proceed to Section 10.1.3, “ Starting VNC Server” . 1 0 .1 .2 .1 . Co nfiguring VNC Se rve r fo r T wo Use rs If you want to configure more than one user on the same machine, create different template-type service files, one for each user. 1. Create two service files, for example vncserver-USER_1@ . servi ce and vncserver-USER_2@ . servi ce. In both these files substitute USER with the correct user name. 2. Set passwords for both users: ~ ]$ su - USER_1 ~ ]$ vncpasswd Password: Verify: ~ ]$ su - USER_2 ~ ]$ vncpasswd Password: Verify: 10.1.3. St art ing VNC Server 133 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To start or enable the service, specify the display number directly in the command. The file configured above in Procedure 10.1, “ Configuring a VNC D isplay for a Single User” works as a template, in which %i is substituted with the display number by systemd . With a valid display number, execute the following command: ~ ]# systemctl start vncserver@ : display_number. servi ce You can also enable the service to start automatically at system start. Then, when you log in, vncserver is automatically started. As ro o t, issue a command as follows: ~ ]# systemctl enabl e vncserver@ : display_number. servi ce At this point, other users are able to use a VNC viewer program to connect to the VNC server using the display number and password defined. Provided a graphical desktop is installed, an instance of that desktop will be displayed. It will not be the same instance as that currently displayed on the target machine. 1 0 .1 .3.1 . Co nfiguring VNC Se rve r fo r T wo Use rs and T wo Diffe re nt Displays For the two configured VNC servers, vncserver-USER_1@.service and vncserver-USER_2@.service, you can enable different display numbers. For example, the following commands will cause a VNC server for USER_1 to start on display 3, and a VNC server for USER_2 to start on display 5: ~ ]# systemctl start vncserver-USER _1@ : 3. servi ce ~ ]# systemctl start vncserver-USER _2@ : 5. servi ce 10.1.4 . T erminat ing a VNC Session Similarly to enabling the vncserver service, you can disable the automatic start of the service at system start: ~ ]# systemctl d i sabl e vncserver@ : display_number. servi ce Or, when your system is running, you can stop the service by issuing the following command as ro o t: ~ ]# systemctl sto p vncserver@ : display_number. servi ce 10.2. VNC Viewer vncvi ewer is a program which shows the graphical user interfaces and controls the vncserver remotely. For operating the vncvi ewer, there is a pop-up menu containing entries which perform various actions such as switching in and out of full-screen mode or quitting the viewer. Alternatively, you can operate vncvi ewer through the terminal. Enter vncvi ewer -h on the command line to list vncvi ewer's parameters. 10.2.1. Inst alling VNC Viewer To install the T ig erVN C client, vncvi ewer, issue the following command as ro o t: 134 Chapt er 1 0 . T igerVNC ~ ]# yum i nstal l ti g ervnc 10.2.2. Connect ing t o VNC Server Once the VNC server is configured, you can connect to it from any VNC viewer. Pro ced u re 10.2. C o n n ect in g t o a VN C Server U sin g a G U I 1. Enter the vi ewer command with no arguments, the VNC Vi ewer: C o nnecti o n D etai l s utility appears. It prompts for a VNC server to connect to. 2. If required, to prevent disconnecting any existing VNC connections to the same display, select the option to allow sharing of the desktop as follows: a. Select the O pti o ns button. b. Select the Mi sc. tab. c. Select the Sh ared button. d. Press O K to return to the main menu. 3. Enter an address and display number to connect to: address:display_number 4. Press C o nnect to connect to the VNC server display. 5. You will be prompted to enter the VNC password. This will be the VNC password for the user corresponding to the display number unless a global default VNC password was set. A window appears showing the VNC server desktop. Note that this is not the desktop the normal user sees, it is an Xvnc desktop. Pro ced u re 10.3. C o n n ect in g t o a VN C Server U sin g t h e C LI 1. Enter the vi ewer command with the address and display number as arguments: vncviewer address:display_number Where address is an IP address or host name. 2. Authenticate yourself by entering the VNC password. This will be the VNC password for the user corresponding to the display number unless a global default VNC password was set. 3. A window appears showing the VNC server desktop. Note that this is not the desktop the normal user sees, it is the Xvnc desktop. 1 0 .2 .2 .1 . Co nfiguring t he Fire wall fo r VNC When using a non-encrypted connection, fi rewal l d might block the connection. To allow fi rewal l d to pass the VNC packets, you can open specific ports to T C P traffic. When using the vi a option, traffic is redirected over SSH which is enabled by default in fi rewal l d . 135 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note The default port of VNC server is 5900. To reach the port through which a remote desktop will be accessible, sum the default port and the user's assigned display number. For example, for the second display: 2 + 5900 = 5902. For displays 0 to 3, make use of fi rewal l d 's support for the VNC service by means of the servi ce option as described below. Note that for display numbers greater than 3, the corresponding ports will have to be opened specifically as explained in Procedure 10.5, “ Opening Ports in firewalld” . Pro ced u re 10.4 . En ab lin g VN C Service in f irewalld 1. Run the following command to see the information concerning fi rewal l d settings: ~ ]$ fi rewal l -cmd --l i st-al l 2. To allow all VNC connections from a specific address, use a command as follows: ~]# fi rewal l -cmd --ad d -ri ch-rul e= ' rul e fami l y= "i pv4 " so urce ad d ress= "19 2. 16 8. 122. 116 " servi ce name= vnc-server accept' success See the Red Hat Enterprise Linux 7 Security Guide for more information on the use of firewall rich language commands. 3. To verify the above settings, use a command as follows: ~]# fi rewal l -cmd --l i st-al l public (default, active) interfaces: bond0 bond0.192 sources: services: dhcpv6-client ssh ports: masquerade: no forward-ports: icmp-blocks: rich rules: rule family="ipv4" source address="192.168.122.116" service name="vnc-server" accept To open a specific port or range of ports make use of the --ad d -po rt option to the fi rewal l -cmd command Line tool. For example, VNC display 4 requires port 59 0 4 to be opened for T C P traffic. Pro ced u re 10.5. O p en in g Po rt s in f irewalld 1. To open a port for T C P traffic in the public zone, issue a command as ro o t as follows: ~]# fi rewal l -cmd --zo ne= publ i c --ad d -po rt= 59 0 4 /tcp success 2. To view the ports that are currently open for the public zone, issue a command as follows: 136 Chapt er 1 0 . T igerVNC ~]# fi rewal l -cmd --zo ne= publ i c --l i st-po rts 5904/tcp A port can be removed using the fi rewal l -cmd --zo ne= zone --remo vepo rt= number/protocol command. For more information on opening and closing ports in fi rewal l d , see the Red Hat Enterprise Linux 7 Security Guide. 10.2.3. Connect ing t o VNC Server Using SSH VNC is a clear text network protocol with no security against possible attacks on the communication. To make the communication secure, you can encrypt your server-client connection by using the vi a option. This will create an SSH tunnel between the VNC server and the client. The format of the command to encrypt a VNC server-client connection is as follows: vncviewer -via user@ host:display_number Examp le 10.1. U sin g t h e - via O p t io n 1. To connect to a VNC server using SSH, enter a command as follows: ~ ]$ vncvi ewer -vi a USER _2@ 19 2. 16 8. 2. 10 1: 3 2. When you are prompted to, type the password, and confirm by pressing Enter. 3. A window with a remote desktop appears on your screen. Re st rict ing VNC Acce ss If you prefer only encrypted connections, you can prevent unencrypted connections altogether by using the -l o cal ho st option in the systemd . servi ce file, the ExecStart line: ExecStart=/sbin/runuser -l user -c "/usr/bin/vncserver -localhost %i" This will stop vncserver from accepting connections from anything but the local host and portforwarded connections sent using SSH as a result of the -vi a option. For more information on using SSH, see Chapter 9, OpenSSH. 10.3. Addit ional Resources For more information about TigerVNC, see the resources listed below. Inst alled Document at ion vncserver(1) — The manual page for the VNC server utility. vncvi ewer(1) — The manual page for the VNC viewer. vncpasswd (1) — The manual page for the VNC password command. 137 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Xvnc(1) — The manual page for the Xvnc server configuration options. x0 vncserver(1) — The manual page for the T i g erVNC server for sharing existing X servers. 138 P art V. Servers Part V. Servers This part discusses various topics related to servers such as how to set up a web server or share files and directories over a network. 139 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 11. Web Servers A web server is a network service that serves content to a client over the web. This typically means web pages, but any other documents can be served as well. Web servers are also known as HTTP servers, as they use the hypertext transport protocol (HTTP). 11.1. T he Apache HT T P Server The web server available in Red Hat Enterprise Linux 7 is version 2.4 of the Ap ach e H T T P Server, httpd , an open source web server developed by the Apache Software Foundation. If you are upgrading from a previous release of Red Hat Enterprise Linux, you will need to update the httpd service configuration accordingly. This section reviews some of the newly added features, outlines important changes between Apache HTTP Server 2.4 and version 2.2, and guides you through the update of older configuration files. 11.1.1. Not able Changes The Apache HTTP Server in Red Hat Enterprise Linux 7 has the following changes compared to Red Hat Enterprise Linux 6: h t t p d Service C o n t ro l With the migration away from SysV init scripts, server administrators should switch to using the apachectl and systemctl commands to control the service, in place of the servi ce command. The following examples are specific to the httpd service. The command: service httpd graceful is replaced by apachectl graceful The systemd unit file for httpd has different behavior from the init script as follows: A graceful restart is used by default when the service is reloaded. A graceful stop is used by default when the service is stopped. The command: service httpd configtest is replaced by apachectl configtest Privat e /t mp To enhance system security, the systemd unit file runs the httpd daemon using a private /tmp directory, separate to the system /tmp directory. 14 0 Chapt er 1 1 . Web Servers C o n f ig u rat io n Layo u t Configuration files which load modules are now placed in the /etc/httpd /co nf. mo d ul es. d / directory. Packages that provide additional loadable modules for httpd , such as php, will place a file in this directory. An Incl ud e directive before the main section of the /etc/httpd /co nf/httpd . co nf file is used to include files within the /etc/httpd /co nf. mo d ul es. d / directory. This means any configuration files within co nf. mo d ul es. d are processed before the main body of httpd . co nf. An Incl ud eO pti o nal directive for files within the /etc/httpd /co nf. d directory is placed at the end of the httpd . co nf file. This means the files within /etc/httpd /co nf. d / are now processed after the main body of httpd . co nf. Some additional configuration files are provided by the httpd package itself: /etc/httpd /co nf. d /auto i nd ex. co nf — This configures mod_autoindex directory indexing. /etc/httpd /co nf. d /userd i r. co nf — This configures access to user directories, for example, http: //exampl e. co m/~ username/; such access is disabled by default for security reasons. /etc/httpd /co nf. d /wel co me. co nf — As in previous releases, this configures the welcome page displayed for http: //l o cal ho st/ when no content is present. D ef au lt C o n f ig u rat io n A minimal httpd . co nf file is now provided by default. Many common configuration settings, such as T i meo ut or KeepAl i ve are no longer explicitly configured in the default configuration; hard-coded settings will be used instead, by default. The hard-coded default settings for all configuration directives are specified in the manual. See Section 11.1.13, “ Installable D ocumentation” for more information. In co mp at ib le Syn t ax C h an g es If migrating an existing configuration from h t t p d 2.2 to h t t p d 2.4 , a number of backwards-incompatible changes to the httpd configuration syntax were made which will require changes. See the following Apache document for more information on upgrading http://httpd.apache.org/docs/2.4/upgrading.html Pro cessin g Mo d el In previous releases of Red Hat Enterprise Linux, different multi-processing models (MPM) were made available as different httpd binaries: the forked model, “ prefork” , as /usr/sbi n/httpd , and the thread-based model “ worker” as /usr/sbi n/httpd . wo rker. In Red Hat Enterprise Linux 7, only a single httpd binary is used, and three MPMs are available as loadable modules: worker, prefork (default), and event. Edit the configuration file /etc/httpd /co nf. mo d ul es. d /0 0 -mpm. co nf as required, by adding and removing the comment character # so that only one of the three MPM modules is loaded. Packag in g C h an g es The LD AP authentication and authorization modules are now provided in a separate subpackage, mod_ldap. The new module mo d _sessio n and associated helper modules are provided in a new sub-package, mod_session. The new modules mo d _p ro xy_h t ml and mo d _xml2en c are provided in a new sub-package, mod_proxy_html. These packages are all in the Optional channel. 14 1 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note Before subscribing to the Optional and Supplementary channels see the Scope of Coverage D etails. If you decide to install packages from these channels, follow the steps documented in the article called How to access Optional and Supplementary channels, and -devel packages using Red Hat Subscription Manager (RHSM)? on the Red Hat Customer Portal. Packag in g Filesyst em Layo u t The /var/cache/mo d _pro xy/ directory is no longer provided; instead, the /var/cache/httpd / directory is packaged with a pro xy and ssl subdirectory. Packaged content provided with httpd has been moved from /var/www/ to /usr/share/httpd /: /usr/share/httpd /i co ns/ — The directory containing a set of icons used with directory indices, previously contained in /var/www/i co ns/, has moved to /usr/share/httpd /i co ns. Available at http: //l o cal ho st/i co ns/ in the default configuration; the location and the availability of the icons is configurable in the /etc/httpd /co nf. d /auto i nd ex. co nf file. /usr/share/httpd /manual / — The /var/www/manual / has moved to /usr/share/httpd /manual /. This directory, contained in the httpd-manual package, contains the HTML version of the manual for httpd . Available at http: //l o cal ho st/manual / if the package is installed, the location and the availability of the manual is configurable in the /etc/httpd /co nf. d /manual . co nf file. /usr/share/httpd /erro r/ — The /var/www/erro r/ has moved to /usr/share/httpd /erro r/. Custom multi-language HTTP error pages. Not configured by default, the example configuration file is provided at /usr/share/d o c/httpd -VERSION/httpd -mul ti l ang -erro rd o c. co nf. Au t h en t icat io n , Au t h o riz at io n an d Access C o n t ro l The configuration directives used to control authentication, authorization and access control have changed significantly. Existing configuration files using the O rd er, D eny and Al l o w directives should be adapted to use the new R eq ui re syntax. See the following Apache document for more information http://httpd.apache.org/docs/2.4/howto/auth.html su exec To improve system security, the su exec binary is no longer installed as if by the ro o t user; instead, it has file system capability bits set which allow a more restrictive set of permissions. In conjunction with this change, the su exec binary no longer uses the /var/l o g /httpd /suexec. l o g logfile. Instead, log messages are sent to syslo g ; by default these will appear in the /var/l o g /secure log file. Mo d u le In t erf ace Third-party binary modules built against h t t p d 2.2 are not compatible with h t t p d 2.4 due to changes to the httpd module interface. Such modules will need to be adjusted as necessary for the h t t p d 2.4 module interface, and then rebuilt. A detailed list of the API changes in version 2. 4 is available here: http://httpd.apache.org/docs/2.4/developer/new_api_2_4.html. 14 2 Chapt er 1 1 . Web Servers The ap xs binary used to build modules from source has moved from /usr/sbi n/apxs to /usr/bi n/apxs. R emo ved mo d u les List of httpd modules removed in Red Hat Enterprise Linux 7: mo d _au t h _mysq l, mo d _au t h _p g sq l h t t p d 2.4 provides SQL database authentication support internally in the mo d _au t h n _d b d module. mo d _p erl mo d _p erl is not officially supported with h t t p d 2.4 by upstream. mo d _au t h z _ld ap h t t p d 2.4 provides LD AP support in sub-package mod_ldap using mo d _au t h n z _ld ap . 11.1.2. Updat ing t he Configurat ion To update the configuration files from the Apache HTTP Server version 2.2, take the following steps: 1. Make sure all module names are correct, since they may have changed. Adjust the Lo ad Mo d ul e directive for each module that has been renamed. 2. Recompile all third party modules before attempting to load them. This typically means authentication and authorization modules. 3. If you use the mo d _userd i r module, make sure the UserD i r directive indicating a directory name (typically publ i c_html ) is provided. 4. If you use the Apache HTTP Secure Server, see Section 11.1.8, “ Enabling the mod_ssl Module” for important information on enabling the Secure Sockets Layer (SSL) protocol. Note that you can check the configuration for possible errors by using the following command: ~]# apachectl co nfi g test Syntax OK For more information on upgrading the Apache HTTP Server configuration from version 2.2 to 2.4, see http://httpd.apache.org/docs/2.4/upgrading.html. 11.1.3. Running t he ht t pd Service This section describes how to start, stop, restart, and check the current status of the Apache HTTP Server. To be able to use the httpd service, make sure you have the httpd installed. You can do so by using the following command: ~]# yum i nstal l httpd For more information on the concept of targets and how to manage system services in Red Hat Enterprise Linux in general, see Chapter 8, Managing Services with systemd. 1 1 .1 .3.1 . St art ing t he Se rvice 14 3 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To run the httpd service, type the following at a shell prompt as ro o t: ~]# systemctl start httpd . servi ce If you want the service to start automatically at boot time, use the following command: ~]# systemctl enabl e httpd . servi ce ln -s '/usr/lib/systemd/system/httpd.service' '/etc/systemd/system/multiuser.target.wants/httpd.service' Note If running the Apache HTTP Server as a secure server, a password may be required after the machine boots if using an encrypted private SSL key. 1 1 .1 .3.2 . St o pping t he Se rvice To stop the running httpd service, type the following at a shell prompt as ro o t: ~]# systemctl sto p httpd . servi ce To prevent the service from starting automatically at boot time, type: ~]# systemctl d i sabl e httpd . servi ce rm '/etc/systemd/system/multi-user.target.wants/httpd.service' 1 1 .1 .3.3. Re st art ing t he Se rvice There are three different ways to restart a running httpd service: 1. To restart the service completely, enter the following command as ro o t: ~]# systemctl restart httpd . servi ce This stops the running httpd service and immediately starts it again. Use this command after installing or removing a dynamically loaded module such as PHP. 2. To only reload the configuration, as ro o t, type: ~]# systemctl rel o ad httpd . servi ce This causes the running httpd service to reload its configuration file. Any requests currently being processed will be interrupted, which may cause a client browser to display an error message or render a partial page. 3. To reload the configuration without affecting active requests, enter the following command as ro o t: ~]# apachectl g raceful 14 4 Chapt er 1 1 . Web Servers This causes the running httpd service to reload its configuration file. Any requests currently being processed will continue to use the old configuration. For more information on how to manage system services in Red Hat Enterprise Linux 7, see Chapter 8, Managing Services with systemd. 1 1 .1 .3.4 . Ve rifying t he Se rvice St at us To verify that the httpd service is running, type the following at a shell prompt: ~]# systemctl i s-acti ve httpd . servi ce active 11.1.4 . Edit ing t he Configurat ion Files When the httpd service is started, by default, it reads the configuration from locations that are listed in Table 11.1, “ The httpd service configuration files” . T ab le 11.1. T h e h t t p d service co n f ig u rat io n f iles Pat h D escrip t io n /etc/httpd /co nf/httpd . c o nf /etc/httpd /co nf. d / The main configuration file. An auxiliary directory for configuration files that are included in the main configuration file. Although the default configuration should be suitable for most situations, it is a good idea to become at least familiar with some of the more important configuration options. Note that for any changes to take effect, the web server has to be restarted first. See Section 11.1.3.3, “ Restarting the Service” for more information on how to restart the httpd service. To check the configuration for possible errors, type the following at a shell prompt: ~]# apachectl co nfi g test Syntax OK To make the recovery from mistakes easier, it is recommended that you make a copy of the original file before editing it. 11.1.5. Working wit h Modules Being a modular application, the httpd service is distributed along with a number of Dynamic Shared Objects (D SOs), which can be dynamically loaded or unloaded at runtime as necessary. By default, these modules are located in /usr/l i b/httpd /mo d ul es/ on 32-bit and in /usr/l i b6 4 /httpd /mo d ul es/ on 64-bit systems. 1 1 .1 .5 .1 . Lo ading a Mo dule To load a particular D SO module, use the Lo ad Mo d ul e directive. Note that modules provided by a separate package often have their own configuration file in the /etc/httpd /co nf. d / directory. Examp le 11.1. Lo ad in g t h e mo d _ssl D SO 14 5 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide LoadModule ssl_module modules/mod_ssl.so Once you are finished, restart the web server to reload the configuration. See Section 11.1.3.3, “ Restarting the Service” for more information on how to restart the httpd service. 1 1 .1 .5 .2 . Writ ing a Mo dule If you intend to create a new D SO module, make sure you have the httpd-devel package installed. To do so, enter the following command as ro o t: ~]# yum i nstal l httpd -d evel This package contains the include files, the header files, and the APach e eXt en Sio n (apxs) utility required to compile a module. Once written, you can build the module with the following command: ~]# apxs -i -a -c module_name. c If the build was successful, you should be able to load the module the same way as any other module that is distributed with the Apache HTTP Server. 11.1.6. Set t ing Up Virt ual Host s The Apache HTTP Server's built in virtual hosting allows the server to provide different information based on which IP address, host name, or port is being requested. To create a name-based virtual host, copy the example configuration file /usr/share/d o c/httpd -VERSION/httpd -vho sts. co nf into the /etc/httpd /co nf. d / directory, and replace the @ @ P o rt@ @ and @ @ ServerR o o t@ @ placeholder values. Customize the options according to your requirements as shown in Example 11.2, “ Example virtual host configuration” . Examp le 11.2. Examp le virt u al h o st co n f ig u rat io n ServerAdmin webmaster@ penguin.example.com DocumentRoot "/www/docs/penguin.example.com" ServerName penguin.example.com ServerAlias www.penguin.example.com ErrorLog "/var/log/httpd/dummy-host.example.com-error_log" CustomLog "/var/log/httpd/dummy-host.example.com-access_log" common Note that ServerName must be a valid D NS name assigned to the machine. Thecontainer is highly customizable, and accepts most of the directives available within the main server configuration. D irectives that are not supported within this container include User and G ro up, which were replaced by SuexecUserG ro up. 14 6 Chapt er 1 1 . Web Servers Note If you configure a virtual host to listen on a non-default port, make sure you update the Li sten directive in the global settings section of the /etc/httpd /co nf/httpd . co nf file accordingly. To activate a newly created virtual host, the web server has to be restarted first. See Section 11.1.3.3, “ Restarting the Service” for more information on how to restart the httpd service. 11.1.7. Set t ing Up an SSL Server Secure Sockets Layer (SSL) is a cryptographic protocol that allows a server and a client to communicate securely. Along with its extended and improved version called Transport Layer Security (TLS), it ensures both privacy and data integrity. The Apache HTTP Server in combination with mo d _ssl , a module that uses the OpenSSL toolkit to provide the SSL/TLS support, is commonly referred to as the SSL server. Red Hat Enterprise Linux also supports the use of Mozilla NSS as the TLS implementation. Support for Mozilla NSS is provided by the mo d _nss module. Unlike an HTTP connection that can be read and possibly modified by anybody who is able to intercept it, the use of SSL/TLS over HTTP, referred to as HTTPS, prevents any inspection or modification of the transmitted content. This section provides basic information on how to enable this module in the Apache HTTP Server configuration, and guides you through the process of generating private keys and self-signed certificates. 1 1 .1 .7 .1 . An Ove rvie w o f Ce rt ificat e s and Se curit y Secure communication is based on the use of keys. In conventional or symmetric cryptography, both ends of the transaction have the same key they can use to decode each other's transmissions. On the other hand, in public or asymmetric cryptography, two keys co-exist: a private key that is kept a secret, and a public key that is usually shared with the public. While the data encoded with the public key can only be decoded with the private key, data encoded with the private key can in turn only be decoded with the public key. To provide secure communications using SSL, an SSL server must use a digital certificate signed by a Certificate Authority (CA). The certificate lists various attributes of the server (that is, the server host name, the name of the company, its location, etc.), and the signature produced using the CA's private key. This signature ensures that a particular certificate authority has signed the certificate, and that the certificate has not been modified in any way. When a web browser establishes a new SSL connection, it checks the certificate provided by the web server. If the certificate does not have a signature from a trusted CA, or if the host name listed in the certificate does not match the host name used to establish the connection, it refuses to communicate with the server and usually presents a user with an appropriate error message. By default, most web browsers are configured to trust a set of widely used certificate authorities. Because of this, an appropriate CA should be chosen when setting up a secure server, so that target users can trust the connection, otherwise they will be presented with an error message, and will have to accept the certificate manually. Since encouraging users to override certificate errors can allow an attacker to intercept the connection, you should use a trusted CA whenever possible. For more information on this, see Table 11.2, “ Information about CA lists used by common web browsers” . T ab le 11.2. In f o rmat io n ab o u t C A list s u sed b y co mmo n web b ro wsers 14 7 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Web B ro wser Lin k Mo z illa Firef o x O p era In t ern et Exp lo rer C h ro miu m Mozilla root CA list. Information on root certificates used by Opera. Information on root certificates used by Microsoft Windows. Information on root certificates used by the Chromium project. When setting up an SSL server, you need to generate a certificate request and a private key, and then send the certificate request, proof of the company's identity, and payment to a certificate authority. Once the CA verifies the certificate request and your identity, it will send you a signed certificate you can use with your server. Alternatively, you can create a self-signed certificate that does not contain a CA signature, and thus should be used for testing purposes only. 11.1.8. Enabling t he mod_ssl Module If you intend to set up an SSL or HTTPS server using mo d _ssl , you can n o t have the another application or module, such as mo d _nss configured to use the same port. Port 4 4 3 is the default port for HTTPS. To set up an SSL server using the mo d _ssl module and the OpenSSL toolkit, install the mod_ssl and openssl packages. Enter the following command as ro o t: ~]# yum i nstal l mo d _ssl o penssl This will create the mo d _ssl configuration file at /etc/httpd /co nf. d /ssl . co nf, which is included in the main Apache HTTP Server configuration file by default. For the module to be loaded, restart the httpd service as described in Section 11.1.3.3, “ Restarting the Service” . Important D ue to the vulnerability described in POODLE: SSLv3 vulnerability (CVE-2014-3566), Red Hat recommends disabling SSL and using only T LSv1. 1 or T LSv1. 2. Backwards compatibility can be achieved using T LSv1. 0 . Many products Red Hat supports have the ability to use SSLv2 or SSLv3 protocols, or enable them by default. However, the use of SSLv2 or SSLv3 is now strongly recommended against. 1 1 .1 .8 .1 . Enabling and Disabling SSL and T LS in m o d_ssl To disable and enable specific versions of the SSL and TLS protocol, either do it globally by adding the SSLP ro to co l directive in the “ ## SSL Global Context” section of the configuration file and removing it everywhere else, or edit the default entry under “ # SSL Protocol support” in all “ VirtualHost” sections. If you do not specify it in the per-domain VirtualHost section then it will inherit the settings from the global section. To make sure that a protocol version is being disabled the administrator should either o n ly specify SSLP ro to co l in the “ SSL Global Context” section, or specify it in all per-domain VirtualHost sections. Pro ced u re 11.1. D isab le SSLv2 an d SSLv3 To disable SSL version 2 and SSL version 3, which implies enabling everything except SSL version 2 and SSL version 3, in all VirtualHost sections, proceed as follows: 14 8 Chapt er 1 1 . Web Servers 1. As ro o t, open the /etc/httpd /co nf. d /ssl . co nf file and search for all instances of the SSLP ro to co l directive. By default, the configuration file contains one section that looks as follows: ~]# vi /etc/httpd /co nf. d /ssl . co nf # SSL Protocol support: # List the enable protocol levels with which clients will be able to # connect. Disable SSLv2 access by default: SSLProtocol all -SSLv2 This section is within the VirtualHost section. 2. Edit the SSLP ro to co l line as follows: # SSL Protocol support: # List the enable protocol levels with which clients will be able to # connect. Disable SSLv2 access by default: SSLProtocol all -SSLv2 -SSLv3 Repeat this action for all VirtualHost sections. Save and close the file. 3. Verify that all occurrences of the SSLP ro to co l directive have been changed as follows: ~]# g rep SSLP ro to co l /etc/httpd /co nf. d /ssl . co nf SSLP ro to co l all -SSLv2 -SSLv3 This step is particularly important if you have more than the one default VirtualHost section. 4. Restart the Apache daemon as follows: ~]# systemctl restart httpd Note that any sessions will be interrupted. Pro ced u re 11.2. D isab le All SSL an d T LS Pro t o co ls Excep t T LS 1 an d U p To disable all SSL and TLS protocol versions except TLS version 1 and higher, proceed as follows: 1. As ro o t, open the /etc/httpd /co nf. d /ssl . co nf file and search for all instances of SSLP ro to co l directive. By default the file contains one section that looks as follows: ~]# vi /etc/httpd /co nf. d /ssl . co nf # SSL Protocol support: # List the enable protocol levels with which clients will be able to # connect. Disable SSLv2 access by default: SSLProtocol all -SSLv2 2. Edit the SSLP ro to co l line as follows: # SSL Protocol support: # List the enable protocol levels with which clients will be able to 14 9 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide # connect. Disable SSLv2 access by default: SSLProtocol -all +TLSv1 +TLSv1.1 +TLSv1.2 Save and close the file. 3. Verify the change as follows: ~]# g rep SSLP ro to co l /etc/httpd /co nf. d /ssl . co nf SSLP ro to co l -all +TLSv1 +TLSv1.1 +TLSv1.2 4. Restart the Apache daemon as follows: ~]# systemctl restart httpd Note that any sessions will be interrupted. Pro ced u re 11.3. T est in g t h e St at u s o f SSL an d T LS Pro t o co ls To check which versions of SSL and TLS are enabled or disabled, make use of the o penssl s_cl i ent -co nnect command. The command has the following form: openssl s_client -connect hostname:port -protocol Where port is the port to test and protocol is the protocol version to test for. To test the SSL server running locally, use l o cal ho st as the host name. For example, to test the default port for secure HTTPS connections, port 4 4 3 to see if SSLv3 is enabled, issue a command as follows: 1. ~]# o penssl s_cl i ent -co nnect l o cal ho st: 4 4 3 -ssl 3 CONNECTED(00000003) 139809943877536:error:14094410:SSL routines:SSL3_READ_BYTES:ssl v3 al ert hand shake fai l ure:s3_pkt.c:1257:SSL alert number 40 139809943877536:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl hand shake fai l ure:s3_pkt.c:596: output omitted New, (NONE), C i pher i s (NO NE) Secure Renegotiation IS NOT supported Compression: NONE Expansion: NONE SSL-Session: Protocol : SSLv3 output truncated The above output indicates that the handshake failed and therefore no cipher was negotiated. 2. 150 ~]$ o penssl s_cl i ent -co nnect l o cal ho st: 4 4 3 -tl s1_2 CONNECTED(00000003) depth=0 C = --, ST = SomeState, L = SomeCity, O = SomeOrganization, OU = SomeOrganizationalUnit, CN = localhost.localdomain, emailAddress = root@ localhost.localdomain output omitted New, TLSv1/SSLv3, C i pher i s EC D HE-R SA-AES256 -G C M-SHA384 Server public key is 2048 bit Secure Renegotiation IS supported Chapt er 1 1 . Web Servers Compression: NONE Expansion: NONE SSL-Session: Protocol : TLSv1.2 output truncated The above output indicates that no failure of the handshake occurred and a set of ciphers was negotiated. The o penssl s_cl i ent command options are documented in the s_cl i ent(1) manual page. For more information on the SSLv3 vulnerability and how to test for it, see the Red Hat Knowledgebase article POODLE: SSLv3 vulnerability (CVE-2014-3566). 11.1.9. Enabling t he mod_nss Module If you intend to set up an HTTPS server using mo d _nss, you can n o t have the mod_ssl package installed with its default settings as mo d _ssl will use port 4 4 3 by default, however this is the default HTTPS port. If at all possible, remove the package. To remove mod_ssl, enter the following command as ro o t: ~]# yum remo ve mo d _ssl Note If mo d _ssl is required for other purposes, modify the /etc/httpd /co nf. d /ssl . co nf file to use a port other than 4 4 3 to prevent mo d _ssl conflicting with mo d _nss when its port to listen on is changed to 4 4 3. Only one module can own a port, therefore mo d _nss and mo d _ssl can only co-exist at the same time if they use unique ports. For this reason mo d _nss by default uses 84 4 3, but the default port for HTTPS is port 4 4 3. The port is specified by the Li sten directive as well as in the VirtualHost name or address. Everything in NSS is associated with a “ token” . The software token exists in the NSS database but you can also have a physical token containing certificates. With OpenSSL, discrete certificates and private keys are held in PEM files. With NSS, these are stored in a database. Each certificate and key is associated with a token and each token can have a password protecting it. This password is optional, but if a password is used then the Apache HTTP server needs a copy of it in order to open the database without user intervention at system start. Pro ced u re 11.4 . C o n f ig u rin g mo d _n ss 1. Install mod_nss as ro o t: ~]# yum i nstal l mo d _nss This will create the mo d _nss configuration file at /etc/httpd /co nf. d /nss. co nf. The /etc/httpd /co nf. d / directory is included in the main Apache HTTP Server configuration file by default. For the module to be loaded, restart the httpd service as described in Section 11.1.3.3, “ Restarting the Service” . 151 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 2. As ro o t, open the /etc/httpd /co nf. d /nss. co nf file and search for all instances of the Li sten directive. Edit the Li sten 84 4 3 line as follows: Listen 443 Port 4 4 3 is the default port for HT T P S. 3. Edit the default Vi rtual Ho st _d efaul t_: 84 4 3 line as follows: VirtualHost _default_:443 Edit any other non-default virtual host sections if they exist. Save and close the file. 4. Mozilla NSS stores certificates in a server certificate database indicated by the NSSC erti fi cateD atabase directive in the /etc/httpd /co nf. d /nss. co nf file. By default the path is set to /etc/httpd /al i as, the NSS database created during installation. To view the default NSS database, issue a command as follows: ~]# certuti l -L -d /etc/httpd /al i as Certificate Nickname Attributes Trust SSL,S/MIME,JAR/XPI cacert CTu,Cu,Cu Server-Cert alpha u,pu,u u,u,u In the above command output, Server-C ert is the default NSSNi ckname. The -L option lists all the certificates, or displays information about a named certificate, in a certificate database. The -d option specifies the database directory containing the certificate and key database files. See the certuti l (1) man page for more command line options. 5. To configure mod_nss to use another database, edit the NSSC erti fi cateD atabase line in the /etc/httpd /co nf. d /nss. co nf file. The default file has the following lines within the VirtualHost section. # Server Certificate Database: # The NSS security database directory that holds the certificates and # keys. The database consists of 3 files: cert8.db, key3.db and secmod.db. # Provide the directory that these files exist. NSSCertificateDatabase /etc/httpd/alias In the above command output, al i as is the default NSS database directory, /etc/httpd /al i as/. 6. To apply a password to the default NSS certificate database, use the following command as ro o t: 152 Chapt er 1 1 . Web Servers ~]# certuti l -W -d /etc/httpd /al i as Enter Password or Pin for "NSS Certificate DB": Enter a password which will be used to encrypt your keys. The password should be at least 8 characters long, and should contain at least one non-alphabetic character. Enter new password: Re-enter password: Password changed successfully. 7. Before deploying the HTTPS server, create a new certificate database using a certificate signed by a certificate authority (CA). Examp le 11.3. Ad d in g a C ert if icat e t o t h e Mo z illa N SS d at ab ase The certuti l command is used to add a CA certificate to the NSS database files: certuti l -d /etc/httpd /nss-db-directory/ -A -n "CA_certificate" t C T ,, -a -i certi fi cate. pem The above command adds a CA certificate stored in a PEM-formatted file named certificate.pem. The -d option specifies the NSS database directory containing the certificate and key database files, the -n option sets a name for the certificate, -t C T ,, means that the certificate is trusted to be used in TLS clients and servers. The -A option adds an existing certificate to a certificate database. If the database does not exist it will be created. The -a option allows the use of ASCII format for input or output, and the -i option passes the certi fi cate. pem input file to the command. See the certuti l (1) man page for more command line options. 8. The NSS database should be password protected to safeguard the private key. Examp le 11.4 . Set t in g _a_Passwo rd _f o r_a_Mo z illa_N SS_d at ab ase The certuti l tool can be used set a password for an NSS database as follows: certutil -W -d /etc/httpd/nss-db-directory/ For example, for the default database, issue a command as ro o t as follows: ~]# certuti l -W -d /etc/httpd /al i as Enter Password or Pin for "NSS Certificate DB": Enter a password which will be used to encrypt your keys. The password should be at least 8 characters long, and should contain at least one non-alphabetic character. Enter new password: Re-enter password: Password changed successfully. 9. Configure mo d _nss to use the NSS internal software token by changing the line with the NSSP assP hraseD i al o g directive as follows: 153 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide NSSP assP hraseD i al o g directive as follows: ~]# vi /etc/httpd /co nf. d /nss. co nf NSSPassPhraseDialog file:/etc/httpd/password.conf This is to avoid manual password entry on system start. The software token exists in the NSS database but you can also have a physical token containing your certificates. 10. If the SSL Server Certificate contained in the NSS database is an RSA certificate, make certain that the NSSNi ckname parameter is uncommented and matches the nickname displayed in step 4 above: ~]# vi /etc/httpd /co nf. d /nss. co nf NSSNickname Server-Cert If the SSL Server Certificate contained in the NSS database is an ECC certificate, make certain that the NSSEC C Ni ckname parameter is uncommented and matches the nickname displayed in step 4 above: ~]# vi /etc/httpd /co nf. d /nss. co nf NSSECCNickname Server-Cert Make certain that the NSSC erti fi cateD atabase parameter is uncommented and points to the NSS database directory displayed in step 4 or configured in step 5 above: ~]# vi /etc/httpd /co nf. d /nss. co nf NSSCertificateDatabase /etc/httpd/alias Replace /etc/httpd /al i as with the path to the certificate database to be used. 11. Create the /etc/httpd /passwo rd . co nf file as ro o t: ~]# vi /etc/httpd /passwo rd . co nf Add a line with the following form: internal:password Replacing password with the password that was applied to the NSS security databases in step 6 above. 12. Apply the appropriate ownership and permissions to the /etc/httpd /passwo rd . co nf file: ~]# chg rp apache /etc/httpd /passwo rd . co nf ~]# chmo d 6 4 0 /etc/httpd /passwo rd . co nf ~]# l s -l /etc/httpd /passwo rd . co nf -rw-r-----. 1 root apache 10 Dec 4 17:13 /etc/httpd/password.conf 13. To configure mo d _nss to use the NSS the software token in /etc/httpd /passwo rd . co nf, edit /etc/httpd /co nf. d /nss. co nf as follows: ~]# vi /etc/httpd /co nf. d /nss. co nf 154 Chapt er 1 1 . Web Servers 14. Restart the Apache server for the changes to take effect as described in Section 11.1.3.3, “ Restarting the Service” Important D ue to the vulnerability described in POODLE: SSLv3 vulnerability (CVE-2014-3566), Red Hat recommends disabling SSL and using only T LSv1. 1 or T LSv1. 2. Backwards compatibility can be achieved using T LSv1. 0 . Many products Red Hat supports have the ability to use SSLv2 or SSLv3 protocols, or enable them by default. However, the use of SSLv2 or SSLv3 is now strongly recommended against. 1 1 .1 .9 .1 . Enabling and Disabling SSL and T LS in m o d_nss To disable and enable specific versions of the SSL and TLS protocol, either do it globally by adding the NSSP ro to co l directive in the “ ## SSL Global Context” section of the configuration file and removing it everywhere else, or edit the default entry under “ # SSL Protocol” in all “ VirtualHost” sections. If you do not specify it in the per-domain VirtualHost section then it will inherit the settings from the global section. To make sure that a protocol version is being disabled the administrator should either o n ly specify NSSP ro to co l in the “ SSL Global Context” section, or specify it in all per-domain VirtualHost sections. Pro ced u re 11.5. D isab le All SSL an d T LS Pro t o co ls Excep t T LS 1 an d U p in mo d _n ss To disable all SSL and TLS protocol versions except TLS version 1 and higher, proceed as follows: 1. As ro o t, open the /etc/httpd /co nf. d /nss. co nf file and search for all instances of the NSSP ro to co l directive. By default, the configuration file contains one section that looks as follows: ~]# vi /etc/httpd /co nf. d /nss. co nf # SSL Protocol: output omitted # Since all protocol ranges are completely inclusive, and no protocol in the # middle of a range may be excluded, the entry "NSSProtocol SSLv3,TLSv1.1" # is identical to the entry "NSSProtocol SSLv3,TLSv1.0,TLSv1.1". NSSProtocol SSLv3,TLSv1.0,TLSv1.1 This section is within the VirtualHost section. 2. Edit the NSSP ro to co l line as follows: # SSL Protocol: NSSProtocol TLSv1.0,TLSv1.1 Repeat this action for all VirtualHost sections. 3. Edit the Li sten 84 4 3 line as follows: Listen 443 4. Edit the default Vi rtual Ho st _d efaul t_: 84 4 3 line as follows: 155 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide VirtualHost _default_:443 Edit any other non-default virtual host sections if they exist. Save and close the file. 5. Verify that all occurrences of the NSSP ro to co l directive have been changed as follows: ~]# g rep NSSP ro to co l /etc/httpd /co nf. d /nss. co nf # middle of a range may be excluded, the entry "NSSP ro to co l SSLv3,TLSv1.1" # is identical to the entry "NSSP ro to co l SSLv3,TLSv1.0,TLSv1.1". NSSP ro to co l TLSv1.0,TLSv1.1 This step is particularly important if you have more than one VirtualHost section. 6. Restart the Apache daemon as follows: ~]# servi ce httpd restart Note that any sessions will be interrupted. Pro ced u re 11.6 . T est in g t h e St at u s o f SSL an d T LS Pro t o co ls in mo d _n ss To check which versions of SSL and TLS are enabled or disabled in mo d _n ss, make use of the o penssl s_cl i ent -co nnect command. Install the openssl package as ro o t: ~]# yum i nstal l o penssl The o penssl s_cl i ent -co nnect command has the following form: openssl s_client -connect hostname:port -protocol Where port is the port to test and protocol is the protocol version to test for. To test the SSL server running locally, use l o cal ho st as the host name. For example, to test the default port for secure HTTPS connections, port 4 4 3 to see if SSLv3 is enabled, issue a command as follows: 1. ~]# o penssl s_cl i ent -co nnect l o cal ho st: 4 4 3 -ssl 3 CONNECTED(00000003) 3077773036:error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number:s3_pkt.c:337: output omitted New, (NONE), C i pher i s (NO NE) Secure Renegotiation IS NOT supported Compression: NONE Expansion: NONE SSL-Session: Protocol : SSLv3 output truncated The above output indicates that the handshake failed and therefore no cipher was negotiated. 2. 156 ~]$ o penssl s_cl i ent -co nnect l o cal ho st: 4 4 3 -tl s1 CONNECTED(00000003) depth=1 C = US, O = example.com, CN = Certificate Shack Chapt er 1 1 . Web Servers output omitted New, TLSv1/SSLv3, C i pher i s AES128-SHA Server public key is 1024 bit Secure Renegotiation IS supported Compression: NONE Expansion: NONE SSL-Session: Protocol : TLSv1 output truncated The above output indicates that no failure of the handshake occurred and a set of ciphers was negotiated. The o penssl s_cl i ent command options are documented in the s_cl i ent(1) manual page. For more information on the SSLv3 vulnerability and how to test for it, see the Red Hat Knowledgebase article POODLE: SSLv3 vulnerability (CVE-2014-3566). 11.1.10. Using an Exist ing Key and Cert ificat e If you have a previously created key and certificate, you can configure the SSL server to use these files instead of generating new ones. There are only two situations where this is not possible: 1. You are changing the IP address or domain name. Certificates are issued for a particular IP address and domain name pair. If one of these values changes, the certificate becomes invalid. 2. You have a certificate from VeriSign, and you are changing the server software. VeriSign, a widely used certificate authority, issues certificates for a particular software product, IP address, and domain name. Changing the software product renders the certificate invalid. In either of the above cases, you will need to obtain a new certificate. For more information on this topic, see Section 11.1.11, “ Generating a New Key and Certificate” . If you want to use an existing key and certificate, move the relevant files to the /etc/pki /tl s/pri vate/ and /etc/pki /tl s/certs/ directories respectively. You can do so by issuing the following commands as ro o t: ~]# mv key_file. key /etc/pki /tl s/pri vate/hostname. key ~]# mv certificate. crt /etc/pki /tl s/certs/hostname. crt Then add the following lines to the /etc/httpd /co nf. d /ssl . co nf configuration file: SSLCertificateFile /etc/pki/tls/certs/hostname.crt SSLCertificateKeyFile /etc/pki/tls/private/hostname.key To load the updated configuration, restart the httpd service as described in Section 11.1.3.3, “ Restarting the Service” . Examp le 11.5. U sin g a key an d cert if icat e f ro m t h e R ed H at Secu re Web Server 157 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# mv /etc/httpd /co nf/httpsd . key /etc/pki /tl s/pri vate/peng ui n. exampl e. co m. key ~]# mv /etc/httpd /co nf/httpsd . crt /etc/pki /tl s/certs/peng ui n. exampl e. co m. crt 11.1.11. Generat ing a New Key and Cert ificat e In order to generate a new key and certificate pair, the crypto-utils package must be installed on the system. To install it, enter the following command as ro o t: ~]# yum i nstal l crypto -uti l s This package provides a set of tools to generate and manage SSL certificates and private keys, and includes g en key, the Red Hat Keypair Generation utility that will guide you through the key generation process. Replacing an existing certificate If the server already has a valid certificate and you are replacing it with a new one, specify a different serial number. This ensures that client browsers are notified of this change, update to this new certificate as expected, and do not fail to access the page. To create a new certificate with a custom serial number, as ro o t, use the following command instead of g en key: ~]# o penssl req -x50 9 -new -set_seri al number -key hostname. key o ut hostname. crt Note If there already is a key file for a particular host name in your system, g en key will refuse to start. In this case, remove the existing file using the following command as ro o t: ~]# rm /etc/pki /tl s/pri vate/hostname. key To run the utility enter the g enkey command as ro o t, followed by the appropriate host name (for example, peng ui n. exampl e. co m): ~]# g enkey hostname To complete the key and certificate creation, take the following steps: 1. Review the target locations in which the key and certificate will be stored. 158 Chapt er 1 1 . Web Servers Fig u re 11.1. R u n n in g t h e g en key u t ilit y Use the T ab key to select the Next button, and press Enter to proceed to the next screen. 2. Using the up and d o wn arrow keys, select a suitable key size. Note that while a larger key increases the security, it also increases the response time of your server. The NIST recommends using 20 4 8 bi ts. See NIST Special Publication 800-131A. Fig u re 11.2. Select in g t h e key siz e Once finished, use the T ab key to select the Next button, and press Enter to initiate the random bits generation process. D epending on the selected key size, this may take some time. 159 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 3. D ecide whether you want to send a certificate request to a certificate authority. Fig u re 11.3. G en erat in g a cert if icat e req u est Use the T ab key to select Y es to compose a certificate request, or No to generate a selfsigned certificate. Then press Enter to confirm your choice. 4. Using the Spacebar key, enable ([*]) or disable ([ ]) the encryption of the private key. Fig u re 11.4 . En cryp t in g t h e p rivat e key 160 Chapt er 1 1 . Web Servers Use the T ab key to select the Next button, and press Enter to proceed to the next screen. 5. If you have enabled the private key encryption, enter an adequate passphrase. Note that for security reasons, it is not displayed as you type, and it must be at least five characters long. Fig u re 11.5. En t erin g a p assp h rase Use the T ab key to select the Next button, and press Enter to proceed to the next screen. Do not forget the passphrase Entering the correct passphrase is required in order for the server to start. If you lose it, you will need to generate a new key and certificate. 6. Customize the certificate details. 161 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 11.6 . Sp ecif yin g cert if icat e in f o rmat io n Use the T ab key to select the Next button, and press Enter to finish the key generation. 7. If you have previously enabled the certificate request generation, you will be prompted to send it to a certificate authority. Fig u re 11.7. In st ru ct io n s o n h o w t o sen d a cert if icat e req u est Press Enter to return to a shell prompt. 162 Chapt er 1 1 . Web Servers Once generated, add the key and certificate locations to the /etc/httpd /co nf. d /ssl . co nf configuration file: SSLCertificateFile /etc/pki/tls/certs/hostname.crt SSLCertificateKeyFile /etc/pki/tls/private/hostname.key Finally, restart the httpd service as described in Section 11.1.3.3, “ Restarting the Service” , so that the updated configuration is loaded. 11.1.12. Configure t he Firewall for HT T P and HT T PS Using t he Command Line Red Hat Enterprise Linux does not allow HT T P and HT T P S traffic by default. To enable the system to act as a web server, make use of fi rewal l d 's supported services to enable HT T P and HT T P S traffic to pass through the firewall as required. To enable HT T P using the command line, issue the following command as ro o t: ~]# fi rewal l -cmd --ad d -servi ce http success To enable HT T P S using the command line, issue the following command as ro o t: ~]# fi rewal l -cmd --ad d -servi ce https success Note that these changes will not persist after the next system start. To make permanent changes to the firewall, repeat the commands adding the --permanent option. 1 1 .1 .1 2 .1 . Che cking Ne t wo rk Acce ss fo r Inco m ing HT T PS and HT T PS Using t he Co m m and Line To check what services the firewall is configured to allow, using the command line, issue the following command as ro o t: ~]# fi rewal l -cmd --l i st-al l public (default, active) interfaces: em1 sources: services: dhcpv6-client ssh output truncated In this example taken from a default installation, the firewall is enabled but HT T P and HT T P S have not been allowed to pass through. Once the HT T P and HT T P firewall services are enabled, the servi ces line will appear similar to the following: services: dhcpv6-client http https ssh For more information on enabling firewall services, or opening and closing ports with fi rewal l d , see the Red Hat Enterprise Linux 7 Security Guide. 11.1.13. Addit ional Resources 163 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To learn more about the Apache HTTP Server, see the following resources. Inst alle d Do cum e nt at io n httpd (8) — The manual page for the httpd service containing the complete list of its commandline options. g enkey(1) — The manual page for g enkey utility, provided by the crypto-utils package. apachectl (8) — The manual page for the Apache HTTP Server Control Interface. Inst allable Do cum e nt at io n http://localhost/manual/ — The official documentation for the Apache HTTP Server with the full description of its directives and available modules. Note that in order to access this documentation, you must have the httpd-manual package installed, and the web server must be running. Before accessing the documentation, issue the following commands as ro o t: ~]# yum i nstal l httpd -manual ~]# apachectl g raceful Online Do cum e nt at io n http://httpd.apache.org/ — The official website for the Apache HTTP Server with documentation on all the directives and default modules. http://www.openssl.org/ — The OpenSSL home page containing further documentation, frequently asked questions, links to the mailing lists, and other useful resources. 164 Chapt er 1 2 . Mail Servers Chapter 12. Mail Servers Red Hat Enterprise Linux offers many advanced applications to serve and access email. This chapter describes modern email protocols in use today, and some of the programs designed to send and receive email. 12.1. Email Prot ocols Today, email is delivered using a client/server architecture. An email message is created using a mail client program. This program then sends the message to a server. The server then forwards the message to the recipient's email server, where the message is then supplied to the recipient's email client. To enable this process, a variety of standard network protocols allow different machines, often running different operating systems and using different email programs, to send and receive email. The following protocols discussed are the most commonly used in the transfer of email. 12.1.1. Mail T ransport Prot ocols Mail delivery from a client application to the server, and from an originating server to the destination server, is handled by the Simple Mail Transfer Protocol (SMTP). 1 2 .1 .1 .1 . SMT P The primary purpose of SMTP is to transfer email between mail servers. However, it is critical for email clients as well. To send email, the client sends the message to an outgoing mail server, which in turn contacts the destination mail server for delivery. For this reason, it is necessary to specify an SMTP server when configuring an email client. Under Red Hat Enterprise Linux, a user can configure an SMTP server on the local machine to handle mail delivery. However, it is also possible to configure remote SMTP servers for outgoing mail. One important point to make about the SMTP protocol is that it does not require authentication. This allows anyone on the Internet to send email to anyone else or even to large groups of people. It is this characteristic of SMTP that makes junk email or spam possible. Imposing relay restrictions limits random users on the Internet from sending email through your SMTP server, to other servers on the internet. Servers that do not impose such restrictions are called open relay servers. Red Hat Enterprise Linux 7 provides the Postfix and Sendmail SMTP programs. 12.1.2. Mail Access Prot ocols There are two primary protocols used by email client applications to retrieve email from mail servers: the Post Office Protocol (POP) and the Internet Message Access Protocol (IMAP). 1 2 .1 .2 .1 . POP The default POP server under Red Hat Enterprise Linux is D o veco t and is provided by the dovecot package. 165 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note In order to use D o veco t , first ensure the dovecot package is installed on your system by running, as ro o t: ~]# yum i nstal l d o veco t For more information on installing packages with Yum, see Section 7.2.4, “ Installing Packages” . When using a P O P server, email messages are downloaded by email client applications. By default, most P O P email clients are automatically configured to delete the message on the email server after it has been successfully transferred, however this setting usually can be changed. P O P is fully compatible with important Internet messaging standards, such as Multipurpose Internet Mail Extensions (MIME), which allow for email attachments. P O P works best for users who have one system on which to read email. It also works well for users who do not have a persistent connection to the Internet or the network containing the mail server. Unfortunately for those with slow network connections, P O P requires client programs upon authentication to download the entire content of each message. This can take a long time if any messages have large attachments. The most current version of the standard P O P protocol is P O P 3. There are, however, a variety of lesser-used P O P protocol variants: APOP — P O P 3 with MD 5 authentication. An encoded hash of the user's password is sent from the email client to the server rather than sending an unencrypted password. KPOP — P O P 3 with Kerberos authentication. RPOP — P O P 3 with R P O P authentication. This uses a per-user ID , similar to a password, to authenticate POP requests. However, this ID is not encrypted, so R P O P is no more secure than standard P O P . For added security, it is possible to use Secure Socket Layer (SSL) encryption for client authentication and data transfer sessions. This can be enabled by using the po p3s service, or by using the stunnel application. For more information on securing email communication, see Section 12.5.1, “ Securing Communication” . 1 2 .1 .2 .2 . IMAP The default IMAP server under Red Hat Enterprise Linux is D o veco t and is provided by the dovecot package. See Section 12.1.2.1, “ POP” for information on how to install D o veco t . When using an IMAP mail server, email messages remain on the server where users can read or delete them. IMAP also allows client applications to create, rename, or delete mail directories on the server to organize and store email. IMAP is particularly useful for users who access their email using multiple machines. The protocol is also convenient for users connecting to the mail server via a slow connection, because only the email header information is downloaded for messages until opened, saving bandwidth. The user also has the ability to delete messages without viewing or downloading them. 166 Chapt er 1 2 . Mail Servers For convenience, IMAP client applications are capable of caching copies of messages locally, so the user can browse previously read messages when not directly connected to the IMAP server. IMAP , like P O P , is fully compatible with important Internet messaging standards, such as MIME, which allow for email attachments. For added security, it is possible to use SSL encryption for client authentication and data transfer sessions. This can be enabled by using the i maps service, or by using the stunnel program. For more information on securing email communication, see Section 12.5.1, “ Securing Communication” . Other free, as well as commercial, IMAP clients and servers are available, many of which extend the IMAP protocol and provide additional functionality. 1 2 .1 .2 .3. Do ve co t The i map-l o g i n and po p3-l o g i n processes which implement the IMAP and P O P 3 protocols are spawned by the master d o veco t daemon included in the dovecot package. The use of IMAP and P O P is configured through the /etc/d o veco t/d o veco t. co nf configuration file; by default d o veco t runs IMAP and P O P 3 together with their secure versions using SSL. To configure d o veco t to use P O P , complete the following steps: 1. Edit the /etc/d o veco t/d o veco t. co nf configuration file to make sure the pro to co l s variable is uncommented (remove the hash sign (#) at the beginning of the line) and contains the po p3 argument. For example: protocols = imap pop3 lmtp When the pro to co l s variable is left commented out, d o veco t will use the default values as described above. 2. Make the change operational for the current session by running the following command as ro o t: ~]# systemctl restart d o veco t 3. Make the change operational after the next reboot by running the command: ~]# systemctl enabl e d o veco t ln -s '/usr/lib/systemd/system/dovecot' '/etc/systemd/system/multiuser.target.wants/dovecot' Note Please note that d o veco t only reports that it started the IMAP server, but also starts the P O P 3 server. Unlike SMT P , both IMAP and P O P 3 require connecting clients to authenticate using a user name and password. By default, passwords for both protocols are passed over the network unencrypted. To configure SSL on d o veco t: Edit the /etc/d o veco t/co nf. d /10 -ssl . co nf configuration to make sure the ssl _pro to co l s variable is uncommented and contains the ! SSLv2 ! SSLv3 arguments: 167 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ssl_protocols = !SSLv2 !SSLv3 These values ensure that d o veco t avoids SSL versions 2 and also 3, which are both known to be insecure. This is due to the POOD LE SSL vulnerability (CVE-2014-3566). See Resolution for POODLE SSL 3.0 vulnerability (CVE-2014-3566) in Postfix and Dovecot for details. Edit the /etc/pki /d o veco t/d o veco t-o penssl . cnf configuration file as you prefer. However, in a typical installation, this file does not require modification. Rename, move or delete the files /etc/pki /d o veco t/certs/d o veco t. pem and /etc/pki /d o veco t/pri vate/d o veco t. pem. Execute the /usr/l i bexec/d o veco t/mkcert. sh script which creates the d o veco t self signed certificates. These certificates are copied in the /etc/pki /d o veco t/certs and /etc/pki /d o veco t/pri vate directories. To implement the changes, restart d o veco t by issuing the following command as ro o t: ~]# systemctl restart d o veco t More details on d o veco t can be found online at http://www.dovecot.org. 12.2. Email Program Classificat ions In general, all email applications fall into at least one of three classifications. Each classification plays a specific role in the process of moving and managing email messages. While most users are only aware of the specific email program they use to receive and send messages, each one is important for ensuring that email arrives at the correct destination. 12.2.1. Mail T ransport Agent A Mail Transport Agent (MTA) transports email messages between hosts using SMT P . A message may involve several MTAs as it moves to its intended destination. While the delivery of messages between machines may seem rather straightforward, the entire process of deciding if a particular MTA can or should accept a message for delivery is quite complicated. In addition, due to problems from spam, use of a particular MTA is usually restricted by the MTA's configuration or the access configuration for the network on which the MTA resides. Many modern email client programs can act as an MTA when sending email. However, this action should not be confused with the role of a true MTA. The sole reason email client programs are capable of sending email like an MTA is because the host running the application does not have its own MTA. This is particularly true for email client programs on non-UNIX-based operating systems. However, these client programs only send outbound messages to an MTA they are authorized to use and do not directly deliver the message to the intended recipient's email server. Since Red Hat Enterprise Linux offers two MTAs, Postfix and Sendmail, email client programs are often not required to act as an MTA. Red Hat Enterprise Linux also includes a special purpose MTA called Fetchmail. For more information on Postfix, Sendmail, and Fetchmail, see Section 12.3, “ Mail Transport Agents” . 12.2.2. Mail Delivery Agent A Mail Delivery Agent (MDA) is invoked by the MTA to file incoming email in the proper user's mailbox. In many cases, the MD A is actually a Local Delivery Agent (LDA), such as mai l or Procmail. 168 Chapt er 1 2 . Mail Servers Any program that actually handles a message for delivery to the point where it can be read by an email client application can be considered an MD A. For this reason, some MTAs (such as Sendmail and Postfix) can fill the role of an MD A when they append new email messages to a local user's mail spool file. In general, MD As do not transport messages between systems nor do they provide a user interface; MD As distribute and sort messages on the local machine for an email client application to access. 12.2.3. Mail User Agent A Mail User Agent (MUA) is synonymous with an email client application. An MUA is a program that, at a minimum, allows a user to read and compose email messages. Many MUAs are capable of retrieving messages via the P O P or IMAP protocols, setting up mailboxes to store messages, and sending outbound messages to an MTA. MUAs may be graphical, such as Evo lu t io n , or have simple text-based interfaces, such as Mu t t . 12.3. Mail T ransport Agent s Red Hat Enterprise Linux 7 offers two primary MTAs: Postfix and Sendmail. Postfix is configured as the default MTA and Sendmail is considered deprecated. If required to switch the default MTA to Sendmail, you can either uninstall Postfix or use the following command as ro o t to switch to Sendmail: ~]# al ternati ves --co nfi g mta You can also use the following command to enable the desired service: ~]# systemctl enabl e service Similarly, to disable the service, type the following at a shell prompt: ~]# systemctl d i sabl e service For more information on how to manage system services in Red Hat Enterprise Linux 7, see Chapter 8, Managing Services with systemd. 12.3.1. Post fix Originally developed at IBM by security expert and programmer Wietse Venema, Postfix is a Sendmail-compatible MTA that is designed to be secure, fast, and easy to configure. To improve security, Postfix uses a modular design, where small processes with limited privileges are launched by a master daemon. The smaller, less privileged processes perform very specific tasks related to the various stages of mail delivery and run in a changed root environment to limit the effects of attacks. Configuring Postfix to accept network connections from hosts other than the local computer takes only a few minor changes in its configuration file. Yet for those with more complex needs, Postfix provides a variety of configuration options, as well as third party add-ons that make it a very versatile and full-featured MTA. The configuration files for Postfix are human readable and support upward of 250 directives. Unlike Sendmail, no macro processing is required for changes to take effect and the majority of the most commonly used options are described in the heavily commented files. 169 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 1 2 .3.1 .1 . T he De fault Po st fix Inst allat io n The Postfix executable is po stfi x. This daemon launches all related processes needed to handle mail delivery. Postfix stores its configuration files in the /etc/po stfi x/ directory. The following is a list of the more commonly used files: access — Used for access control, this file specifies which hosts are allowed to connect to Postfix. mai n. cf — The global Postfix configuration file. The majority of configuration options are specified in this file. master. cf — Specifies how Postfix interacts with various processes to accomplish mail delivery. transpo rt — Maps email addresses to relay hosts. The al i ases file can be found in the /etc/ directory. This file is shared between Postfix and Sendmail. It is a configurable list required by the mail protocol that describes user ID aliases. Important The default /etc/po stfi x/mai n. cf file does not allow Postfix to accept network connections from a host other than the local computer. For instructions on configuring Postfix as a server for other clients, see Section 12.3.1.3, “ Basic Postfix Configuration” . Restart the po stfi x service after changing any options in the configuration files under the /etc/po stfi x/ directory in order for those changes to take effect. To do so, run the following command as ro o t: ~]# systemctl restart po stfi x 1 2 .3.1 .2 . Upgrading Fro m a Pre vio us Re le ase The following settings in Red Hat Enterprise Linux 7 are different to previous releases: d i sabl e_vrfy_co mmand = no — This is disabled by default, which is different to the default for Sendmail. If changed to yes it can prevent certain email address harvesting methods. al l o w_percent_hack = yes — This is enabled by default. It allows removing % characters in email addresses. The percent hack is an old workaround that allowed sender-controlled routing of email messages. D NS and mail routing are now much more reliable, but Postfix continues to support the hack. To turn off percent rewriting, set al l o w_percent_hack to no . smtpd _hel o _req ui red = no — This is disabled by default, as it is in Sendmail, because it can prevent some applications from sending mail. It can be changed to yes to require clients to send the HELO or EHLO commands before attempting to send the MAIL, FROM, or ETRN commands. 1 2 .3.1 .3. Basic Po st fix Co nfigurat io n By default, Postfix does not accept network connections from any host other than the local host. Perform the following steps as ro o t to enable mail delivery for other hosts on the network: 170 Chapt er 1 2 . Mail Servers Edit the /etc/po stfi x/mai n. cf file with a text editor, such as vi . Uncomment the myd o mai n line by removing the hash sign (#), and replace domain.tld with the domain the mail server is servicing, such as exampl e. co m. Uncomment the myo ri g i n = $myd o mai n line. Uncomment the myho stname line, and replace host.domain.tld with the host name for the machine. Uncomment the myd esti nati o n = $myho stname, l o cal ho st. $myd o mai n line. Uncomment the mynetwo rks line, and replace 168.100.189.0/28 with a valid network setting for hosts that can connect to the server. Uncomment the i net_i nterfaces = al l line. Comment the i net_i nterfaces = l o cal ho st line. Restart the po stfi x service. Once these steps are complete, the host accepts outside emails for delivery. Postfix has a large assortment of configuration options. One of the best ways to learn how to configure Postfix is to read the comments within the /etc/po stfi x/mai n. cf configuration file. Additional resources including information about Postfix configuration, SpamAssassin integration, or detailed descriptions of the /etc/po stfi x/mai n. cf parameters are available online at http://www.postfix.org/. 1 2 .3.1 .4 . Using Po st fix wit h LDAP Postfix can use an LD AP directory as a source for various lookup tables (e.g.: al i ases, vi rtual , cano ni cal , etc.). This allows LD AP to store hierarchical user information and Postfix to only be given the result of LD AP queries when needed. By not storing this information locally, administrators can easily maintain it. 12.3.1.4 .1. T h e /et c/aliases lo o ku p examp le The following is a basic example for using LD AP to look up the /etc/al i ases file. Make sure your /etc/po stfi x/mai n. cf file contains the following: alias_maps = hash:/etc/aliases, ldap:/etc/postfix/ldap-aliases.cf Create a /etc/po stfi x/l d ap-al i ases. cf file if you do not have one already and make sure it contains the following: server_host = ldap.example.com search_base = dc=example, dc=com where ldap.example.com, example, and com are parameters that need to be replaced with specification of an existing available LD AP server. 171 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note The /etc/po stfi x/l d ap-al i ases. cf file can specify various parameters, including parameters that enable LD AP SSL and ST AR T T LS. For more information, see the l d ap_tabl e(5) man page. For more information on LD AP , see Section 13.1, “ OpenLD AP” . 12.3.2. Sendmail Sendmail's core purpose, like other MTAs, is to safely transfer email among hosts, usually using the SMT P protocol. Note that Sendmail is considered deprecated and users are encouraged to use Postfix when possible. See Section 12.3.1, “ Postfix” for more information. 1 2 .3.2 .1 . Purpo se and Lim it at io ns It is important to be aware of what Sendmail is and what it can do, as opposed to what it is not. In these days of monolithic applications that fulfill multiple roles, Sendmail may seem like the only application needed to run an email server within an organization. Technically, this is true, as Sendmail can spool mail to each users' directory and deliver outbound mail for users. However, most users actually require much more than simple email delivery. Users usually want to interact with their email using an MUA, that uses P O P or IMAP , to download their messages to their local machine. Or, they may prefer a Web interface to gain access to their mailbox. These other applications can work in conjunction with Sendmail, but they actually exist for different reasons and can operate separately from one another. It is beyond the scope of this section to go into all that Sendmail should or could be configured to do. With literally hundreds of different options and rule sets, entire volumes have been dedicated to helping explain everything that can be done and how to fix things that go wrong. See the Section 12.6, “ Additional Resources” for a list of Sendmail resources. This section reviews the files installed with Sendmail by default and reviews basic configuration changes, including how to stop unwanted email (spam) and how to extend Sendmail with the Lightweight Directory Access Protocol (LDAP). 1 2 .3.2 .2 . T he De fault Se ndm ail Inst allat io n In order to use Sendmail, first ensure the sendmail package is installed on your system by running, as ro o t: ~]# yum i nstal l send mai l In order to configure Sendmail, ensure the sendmail-cf package is installed on your system by running, as ro o t: ~]# yum i nstal l send mai l -cf For more information on installing packages with Yum, see Section 7.2.4, “ Installing Packages” . Before using Sendmail, the default MTA has to be switched from Postfix. For more information how to switch the default MTA refer to Section 12.3, “ Mail Transport Agents” . The Sendmail executable is send mai l . 172 Chapt er 1 2 . Mail Servers Sendmail's lengthy and detailed configuration file is /etc/mai l /send mai l . cf. Avoid editing the send mai l . cf file directly. To make configuration changes to Sendmail, edit the /etc/mai l /send mai l . mc file, back up the original /etc/mai l /send mai l . cf file, and use the following alternatives to generate a new configuration file: Use the included makefile in /etc/mai l / to create a new /etc/mai l /send mai l . cf configuration file: ~]# make al l -C /etc/mai l / All other generated files in /etc/mai l (db files) will be regenerated if needed. The old makemap commands are still usable. The make command is automatically used whenever you start or restart the send mai l service. More information on configuring Sendmail can be found in Section 12.3.2.3, “ Common Sendmail Configuration Changes” . Various Sendmail configuration files are installed in the /etc/mai l / directory including: access — Specifies which systems can use Sendmail for outbound email. d o mai ntabl e — Specifies domain name mapping. l o cal -ho st-names — Specifies aliases for the host. mai l ertabl e — Specifies instructions that override routing for particular domains. vi rtusertabl e — Specifies a domain-specific form of aliasing, allowing multiple virtual domains to be hosted on one machine. Several of the configuration files in the /etc/mai l / directory, such as access, d o mai ntabl e, mai l ertabl e and vi rtusertabl e, must actually store their information in database files before Sendmail can use any configuration changes. To include any changes made to these configurations in their database files, run the following commands, as ro o t: ~]# cd /etc/mai l / ~]# make al l This will update vi rtusertabl e. d b, access. d b, d o mai ntabl e. d b, mai l ertabl e. d b, send mai l . cf, and submi t. cf. To update all the database files listed above and to update a custom database file, use a command in the following format: make name.db al l where name represents the name of the custom database file to be updated. To update a single database, use a command in the following format: make name.db where name.db represents the name of the database file to be updated. You may also restart the send mai l service for the changes to take effect by running: ~]# systemctl restart send mai l 173 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide For example, to have all emails addressed to the exampl e. co m domain delivered to bo b@ o therexampl e. co m, add the following line to the vi rtusertabl e file: @ exampl e. co m bo b@ o ther-exampl e. co m To finalize the change, the vi rtusertabl e. d b file must be updated: ~]# make vi rtusertabl e. d b al l Using the al l option will result in the vi rtusertabl e. d b and access. d b being updated at the same time. 1 2 .3.2 .3. Co m m o n Se ndm ail Co nfigurat io n Change s When altering the Sendmail configuration file, it is best not to edit an existing file, but to generate an entirely new /etc/mai l /send mai l . cf file. Warning Before replacing or making any changes to the send mai l . cf file, create a backup copy. To add the desired functionality to Sendmail, edit the /etc/mai l /send mai l . mc file as ro o t. Once you are finished, restart the send mai l service and, if the m4 package is installed, the m4 macro processor will automatically generate a new send mai l . cf configuration file: ~]# systemctl restart send mai l Important The default send mai l . cf file does not allow Sendmail to accept network connections from any host other than the local computer. To configure Sendmail as a server for other clients, edit the /etc/mai l /send mai l . mc file, and either change the address specified in the Ad d r= option of the D AEMO N_O P T IO NS directive from 127. 0 . 0 . 1 to the IP address of an active network device or comment out the D AEMO N_O P T IO NS directive all together by placing d nl at the beginning of the line. When finished, regenerate /etc/mai l /send mai l . cf by restarting the service: ~]# systemctl restart send mai l The default configuration in Red Hat Enterprise Linux works for most SMT P -only sites. However, it does not work for UUCP (UNIX-to-UNIX Copy Protocol) sites. If using UUCP mail transfers, the /etc/mai l /send mai l . mc file must be reconfigured and a new /etc/mai l /send mai l . cf file must be generated. Consult the /usr/share/send mai l -cf/R EAD ME file before editing any files in the directories under the /usr/share/send mai l -cf/ directory, as they can affect the future configuration of the /etc/mai l /send mai l . cf file. 174 Chapt er 1 2 . Mail Servers 1 2 .3.2 .4 . Masque rading One common Sendmail configuration is to have a single machine act as a mail gateway for all machines on the network. For example, a company may want to have a machine called mai l . exampl e. co m that handles all of their email and assigns a consistent return address to all outgoing mail. In this situation, the Sendmail server must masquerade the machine names on the company network so that their return address is user@ exampl e. co m instead of user@ ho st. exampl e. co m. To do this, add the following lines to /etc/mai l /send mai l . mc: FEATURE(always_add_domain)dnl FEATURE(`masquerade_entire_domain')dnl FEATURE(`masquerade_envelope')dnl FEATURE(`allmasquerade')dnl MASQUERADE_AS(`example.com.')dnl MASQUERADE_DOMAIN(`example.com.')dnl MASQUERADE_AS(example.com)dnl After generating a new send mai l . cf file using the m4 macro processor, this configuration makes all mail from inside the network appear as if it were sent from exampl e. co m. Note that administrators of mail servers, D NS and D HC P servers, as well as any provisioning applications, should agree on the host name format used in an organization. See the Red Hat Enterprise Linux 7 Networking Guide for more information on recommended naming practices. 1 2 .3.2 .5 . St o pping Spam Email spam can be defined as unnecessary and unwanted email received by a user who never requested the communication. It is a disruptive, costly, and widespread abuse of Internet communication standards. Sendmail makes it relatively easy to block new spamming techniques being employed to send junk email. It even blocks many of the more usual spamming methods by default. Main anti-spam features available in sendmail are header checks, relaying denial (default from version 8.9), access database and sender information checks. For example, forwarding of SMT P messages, also called relaying, has been disabled by default since Sendmail version 8.9. Before this change occurred, Sendmail directed the mail host (x. ed u) to accept messages from one party (y. co m) and sent them to a different party (z. net). Now, however, Sendmail must be configured to permit any domain to relay mail through the server. To configure relay domains, edit the /etc/mai l /rel ay-d o mai ns file and restart Sendmail ~]# systemctl restart send mai l However users can also be sent spam from from servers on the Internet. In these instances, Sendmail's access control features available through the /etc/mai l /access file can be used to prevent connections from unwanted hosts. The following example illustrates how this file can be used to both block and specifically allow access to the Sendmail server: bad spammer. co m ER R O R : 550 "G o away and d o no t spam us anymo re" tux. bad spammer. co m O K 10 . 0 R ELAY 175 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide This example shows that any email sent from bad spammer. co m is blocked with a 550 RFC-821 compliant error code, with a message sent back. Email sent from the tux. bad spammer. co m subdomain, is accepted. The last line shows that any email sent from the 10.0.*.* network can be relayed through the mail server. Because the /etc/mai l /access. d b file is a database, use the makemap command to update any changes. D o this using the following command as ro o t: ~]# makemap hash /etc/mai l /access < /etc/mai l /access Message header analysis allows you to reject mail based on header contents. SMT P servers store information about an email's journey in the message header. As the message travels from one MTA to another, each puts in a R ecei ved header above all the other R ecei ved headers. It is important to note that this information may be altered by spammers. The above examples only represent a small part of what Sendmail can do in terms of allowing or blocking access. See the /usr/share/send mai l -cf/R EAD ME file for more information and examples. Since Sendmail calls the Procmail MD A when delivering mail, it is also possible to use a spam filtering program, such as SpamAssassin, to identify and file spam for users. See Section 12.4.2.6, “ Spam Filters” for more information about using SpamAssassin. 1 2 .3.2 .6 . Using Se ndm ail wit h LDAP Using LD AP is a very quick and powerful way to find specific information about a particular user from a much larger group. For example, an LD AP server can be used to look up a particular email address from a common corporate directory by the user's last name. In this kind of implementation, LD AP is largely separate from Sendmail, with LD AP storing the hierarchical user information and Sendmail only being given the result of LD AP queries in pre-addressed email messages. However, Sendmail supports a much greater integration with LD AP , where it uses LD AP to replace separately maintained files, such as /etc/al i ases and /etc/mai l /vi rtusertabl es, on different mail servers that work together to support a medium- to enterprise-level organization. In short, LD AP abstracts the mail routing level from Sendmail and its separate configuration files to a powerful LD AP cluster that can be leveraged by many different applications. The current version of Sendmail contains support for LD AP . To extend the Sendmail server using LD AP , first get an LD AP server, such as O p en LD AP, running and properly configured. Then edit the /etc/mai l /send mai l . mc to include the following: LDAPROUTE_DOMAIN('yourdomain.com')dnl FEATURE('ldap_routing')dnl Note This is only for a very basic configuration of Sendmail with LD AP . The configuration can differ greatly from this depending on the implementation of LD AP , especially when configuring several Sendmail machines to use a common LD AP server. Consult /usr/share/send mai l -cf/R EAD ME for detailed LD AP routing configuration instructions and examples. 176 Chapt er 1 2 . Mail Servers Next, recreate the /etc/mai l /send mai l . cf file by running the m4 macro processor and again restarting Sendmail. See Section 12.3.2.3, “ Common Sendmail Configuration Changes” for instructions. For more information on LD AP , see Section 13.1, “ OpenLD AP” . 12.3.3. Fet chmail Fetchmail is an MTA which retrieves email from remote servers and delivers it to the local MTA. Many users appreciate the ability to separate the process of downloading their messages located on a remote server from the process of reading and organizing their email in an MUA. D esigned with the needs of dial-up users in mind, Fetchmail connects and quickly downloads all of the email messages to the mail spool file using any number of protocols, including P O P 3 and IMAP . It can even forward email messages to an SMT P server, if necessary. Note In order to use Fet ch mail, first ensure the fetchmail package is installed on your system by running, as ro o t: ~]# yum i nstal l fetchmai l For more information on installing packages with Yum, see Section 7.2.4, “ Installing Packages” . Fetchmail is configured for each user through the use of a . fetchmai l rc file in the user's home directory. If it does not already exist, create the . fetchmai l rc file in your home directory Using preferences in the . fetchmai l rc file, Fetchmail checks for email on a remote server and downloads it. It then delivers it to port 25 on the local machine, using the local MTA to place the email in the correct user's spool file. If Procmail is available, it is launched to filter the email and place it in a mailbox so that it can be read by an MUA. 1 2 .3.3.1 . Fe t chm ail Co nfigurat io n Opt io ns Although it is possible to pass all necessary options on the command line to check for email on a remote server when executing Fetchmail, using a . fetchmai l rc file is much easier. Place any desired configuration options in the . fetchmai l rc file for those options to be used each time the fetchmai l command is issued. It is possible to override these at the time Fetchmail is run by specifying that option on the command line. A user's . fetchmai l rc file contains three classes of configuration options: global options — Gives Fetchmail instructions that control the operation of the program or provide settings for every connection that checks for email. server options — Specifies necessary information about the server being polled, such as the host name, as well as preferences for specific email servers, such as the port to check or number of seconds to wait before timing out. These options affect every user using that server. user options — Contains information, such as user name and password, necessary to authenticate and check for email using a specified email server. Global options appear at the top of the . fetchmai l rc file, followed by one or more server options, 177 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide each of which designate a different email server that Fetchmail should check. User options follow server options for each user account checking that email server. Like server options, multiple user options may be specified for use with a particular server as well as to check multiple email accounts on the same server. Server options are called into service in the . fetchmai l rc file by the use of a special option verb, po l l or ski p, that precedes any of the server information. The po l l action tells Fetchmail to use this server option when it is run, which checks for email using the specified user options. Any server options after a ski p action, however, are not checked unless this server's host name is specified when Fetchmail is invoked. The ski p option is useful when testing configurations in the . fetchmai l rc file because it only checks skipped servers when specifically invoked, and does not affect any currently working configurations. The following is an example of a . fetchmai l rc file: set postmaster "user1" set bouncemail poll pop.domain.com proto pop3 user 'user1' there with password 'secret' is user1 here poll mail.domain2.com user 'user5' there with password 'secret2' is user1 here user 'user7' there with password 'secret3' is user1 here In this example, the global options specify that the user is sent email as a last resort (po stmaster option) and all email errors are sent to the postmaster instead of the sender (bo uncemai l option). The set action tells Fetchmail that this line contains a global option. Then, two email servers are specified, one set to check using P O P 3, the other for trying various protocols to find one that works. Two users are checked using the second server option, but all email found for any user is sent to user1's mail spool. This allows multiple mailboxes to be checked on multiple servers, while appearing in a single MUA inbox. Each user's specific information begins with the user action. Note Users are not required to place their password in the . fetchmai l rc file. Omitting the wi th passwo rd ' password' section causes Fetchmail to ask for a password when it is launched. Fetchmail has numerous global, server, and local options. Many of these options are rarely used or only apply to very specific situations. The fetchmai l man page explains each option in detail, but the most common ones are listed in the following three sections. 1 2 .3.3.2 . Glo bal Opt io ns Each global option should be placed on a single line after a set action. d aemo n seconds — Specifies daemon-mode, where Fetchmail stays in the background. Replace seconds with the number of seconds Fetchmail is to wait before polling the server. po stmaster — Specifies a local user to send mail to in case of delivery problems. sysl o g — Specifies the log file for errors and status messages. By default, this is /var/l o g /mai l l o g . 178 Chapt er 1 2 . Mail Servers 1 2 .3.3.3. Se rve r Opt io ns Server options must be placed on their own line in . fetchmai l rc after a po l l or ski p action. auth auth-type — Replace auth-type with the type of authentication to be used. By default, passwo rd authentication is used, but some protocols support other types of authentication, including kerbero s_v5, kerbero s_v4 , and ssh. If the any authentication type is used, Fetchmail first tries methods that do not require a password, then methods that mask the password, and finally attempts to send the password unencrypted to authenticate to the server. i nterval number — Polls the specified server every number of times that it checks for email on all configured servers. This option is generally used for email servers where the user rarely receives messages. po rt port-number — Replace port-number with the port number. This value overrides the default port number for the specified protocol. pro to protocol — Replace protocol with the protocol, such as po p3 or i map, to use when checking for messages on the server. ti meo ut seconds — Replace seconds with the number of seconds of server inactivity after which Fetchmail gives up on a connection attempt. If this value is not set, a default of 30 0 seconds is used. 1 2 .3.3.4 . Use r Opt io ns User options may be placed on their own lines beneath a server option or on the same line as the server option. In either case, the defined options must follow the user option (defined below). fetchal l — Orders Fetchmail to download all messages in the queue, including messages that have already been viewed. By default, Fetchmail only pulls down new messages. fetchl i mi t number — Replace number with the number of messages to be retrieved before stopping. fl ush — D eletes all previously viewed messages in the queue before retrieving new messages. l i mi t max-number-bytes — Replace max-number-bytes with the maximum size in bytes that messages are allowed to be when retrieved by Fetchmail. This option is useful with slow network links, when a large message takes too long to download. passwo rd ' password' — Replace password with the user's password. preco nnect "command" — Replace command with a command to be executed before retrieving messages for the user. po stco nnect "command" — Replace command with a command to be executed after retrieving messages for the user. ssl — Activates SSL encryption. user "username" — Replace username with the username used by Fetchmail to retrieve messages. This option must precede all other user options. 1 2 .3.3.5 . Fe t chm ail Co m m and Opt io ns 179 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Most Fetchmail options used on the command line when executing the fetchmai l command mirror the . fetchmai l rc configuration options. In this way, Fetchmail may be used with or without a configuration file. These options are not used on the command line by most users because it is easier to leave them in the . fetchmai l rc file. There may be times when it is desirable to run the fetchmai l command with other options for a particular purpose. It is possible to issue command options to temporarily override a . fetchmai l rc setting that is causing an error, as any options specified at the command line override configuration file options. 1 2 .3.3.6 . Info rm at io nal o r De bugging Opt io ns Certain options used after the fetchmai l command can supply important information. --co nfi g d ump — D isplays every possible option based on information from . fetchmai l rc and Fetchmail defaults. No email is retrieved for any users when using this option. -s — Executes Fetchmail in silent mode, preventing any messages, other than errors, from appearing after the fetchmai l command. -v — Executes Fetchmail in verbose mode, displaying every communication between Fetchmail and remote email servers. -V — D isplays detailed version information, lists its global options, and shows settings to be used with each user, including the email protocol and authentication method. No email is retrieved for any users when using this option. 1 2 .3.3.7 . Spe cial Opt io ns These options are occasionally useful for overriding defaults often found in the . fetchmai l rc file. -a — Fetchmail downloads all messages from the remote email server, whether new or previously viewed. By default, Fetchmail only downloads new messages. -k — Fetchmail leaves the messages on the remote email server after downloading them. This option overrides the default behavior of deleting messages after downloading them. -l max-number-bytes — Fetchmail does not download any messages over a particular size and leaves them on the remote email server. --q ui t — Quits the Fetchmail daemon process. More commands and . fetchmai l rc options can be found in the fetchmai l man page. 12.3.4 . Mail T ransport Agent (MT A) Configurat ion A Mail Transport Agent (MTA) is essential for sending email. A Mail User Agent (MUA) such as Evo lu t io n or Mu t t , is used to read and compose email. When a user sends an email from an MUA, the message is handed off to the MTA, which sends the message through a series of MTAs until it reaches its destination. Even if a user does not plan to send email from the system, some automated tasks or system programs might use the mai l command to send email containing log messages to the ro o t user of the local system. Red Hat Enterprise Linux 7 provides two MTAs: Postfix and Sendmail. If both are installed, Postfix is the default MTA. Note that Sendmail is considered deprecated in Red Hat Enterprise Linux 7. 180 Chapt er 1 2 . Mail Servers 12.4 . Mail Delivery Agent s Red Hat Enterprise Linux includes two primary MD As, Procmail and mai l . Both of the applications are considered LD As and both move email from the MTA's spool file into the user's mailbox. However, Procmail provides a robust filtering system. This section details only Procmail. For information on the mai l command, consult its man page (man mai l ). Procmail delivers and filters email as it is placed in the mail spool file of the localhost. It is powerful, gentle on system resources, and widely used. Procmail can play a critical role in delivering email to be read by email client applications. Procmail can be invoked in several different ways. Whenever an MTA places an email into the mail spool file, Procmail is launched. Procmail then filters and files the email for the MUA and quits. Alternatively, the MUA can be configured to execute Procmail any time a message is received so that messages are moved into their correct mailboxes. By default, the presence of /etc/pro cmai l rc or of a ~ /. pro cmai l rc file (also called an rc file) in the user's home directory invokes Procmail whenever an MTA receives a new message. By default, no system-wide rc files exist in the /etc/ directory and no . pro cmai l rc files exist in any user's home directory. Therefore, to use Procmail, each user must construct a . pro cmai l rc file with specific environment variables and rules. Whether Procmail acts upon an email message depends upon whether the message matches a specified set of conditions or recipes in the rc file. If a message matches a recipe, then the email is placed in a specified file, is deleted, or is otherwise processed. When Procmail starts, it reads the email message and separates the body from the header information. Next, Procmail looks for a /etc/pro cmai l rc file and rc files in the /etc/pro cmai l rcs directory for default, system-wide, Procmail environmental variables and recipes. Procmail then searches for a . pro cmai l rc file in the user's home directory. Many users also create additional rc files for Procmail that are referred to within the . pro cmai l rc file in their home directory. 12.4 .1. Procmail Configurat ion The Procmail configuration file contains important environmental variables. These variables specify things such as which messages to sort and what to do with the messages that do not match any recipes. These environmental variables usually appear at the beginning of the ~ /. pro cmai l rc file in the following format: env-variable="value" In this example, env-variable is the name of the variable and value defines the variable. There are many environment variables not used by most Procmail users and many of the more important environment variables are already defined by a default value. Most of the time, the following variables are used: D EFAULT — Sets the default mailbox where messages that do not match any recipes are placed. The default D EFAULT value is the same as $O R G MAIL. 181 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide INC LUD ER C — Specifies additional rc files containing more recipes for messages to be checked against. This breaks up the Procmail recipe lists into individual files that fulfill different roles, such as blocking spam and managing email lists, that can then be turned off or on by using comment characters in the user's ~ /. pro cmai l rc file. For example, lines in a user's ~ /. pro cmai l rc file may look like this: MAILDIR=$HOME/Msgs INCLUDERC=$MAILDIR/lists.rc INCLUDERC=$MAILDIR/spam.rc To turn off Procmail filtering of email lists but leaving spam control in place, comment out the first INC LUD ER C line with a hash sign (#). Note that it uses paths relative to the current directory. LO C KSLEEP — Sets the amount of time, in seconds, between attempts by Procmail to use a particular lockfile. The default is 8 seconds. LO C KT IMEO UT — Sets the amount of time, in seconds, that must pass after a lockfile was last modified before Procmail assumes that the lockfile is old and can be deleted. The default is 10 24 seconds. LO G FILE — The file to which any Procmail information or error messages are written. MAILD IR — Sets the current working directory for Procmail. If set, all other Procmail paths are relative to this directory. O R G MAIL — Specifies the original mailbox, or another place to put the messages if they cannot be placed in the default or recipe-required location. By default, a value of /var/spo o l /mai l /$LO G NAME is used. SUSP END — Sets the amount of time, in seconds, that Procmail pauses if a necessary resource, such as swap space, is not available. SWIT C HR C — Allows a user to specify an external file containing additional Procmail recipes, much like the INC LUD ER C option, except that recipe checking is actually stopped on the referring configuration file and only the recipes on the SWIT C HR C -specified file are used. VER BO SE — Causes Procmail to log more information. This option is useful for debugging. Other important environmental variables are pulled from the shell, such as LO G NAME, the login name; HO ME, the location of the home directory; and SHELL, the default shell. A comprehensive explanation of all environments variables, and their default values, is available in the pro cmai l rc man page. 12.4 .2. Procmail Recipes New users often find the construction of recipes the most difficult part of learning to use Procmail. This difficulty is often attributed to recipes matching messages by using regular expressions which are used to specify qualifications for string matching. However, regular expressions are not very difficult to construct and even less difficult to understand when read. Additionally, the consistency of the way Procmail recipes are written, regardless of regular expressions, makes it easy to learn by example. To see example Procmail recipes, see Section 12.4.2.5, “ Recipe Examples” . Procmail recipes take the following form: :0 [flags] [: lockfile-name ] 182 Chapt er 1 2 . Mail Servers * [ condition_1_special-condition-character condition_1_regular_expression ] * [ condition_2_special-condition-character condition2_regular_expression ] * [ condition_N_special-condition-character conditionN_regular_expression ] special-action-character action-to-perform The first two characters in a Procmail recipe are a colon and a zero. Various flags can be placed after the zero to control how Procmail processes the recipe. A colon after the flags section specifies that a lockfile is created for this message. If a lockfile is created, the name can be specified by replacing lockfile-name. A recipe can contain several conditions to match against the message. If it has no conditions, every message matches the recipe. Regular expressions are placed in some conditions to facilitate message matching. If multiple conditions are used, they must all match for the action to be performed. Conditions are checked based on the flags set in the recipe's first line. Optional special characters placed after the asterisk character (*) can further control the condition. The action-to-perform argument specifies the action taken when the message matches one of the conditions. There can only be one action per recipe. In many cases, the name of a mailbox is used here to direct matching messages into that file, effectively sorting the email. Special action characters may also be used before the action is specified. See Section 12.4.2.4, “ Special Conditions and Actions” for more information. 1 2 .4 .2 .1 . De live ring vs. No n-De live ring Re cipe s The action used if the recipe matches a particular message determines whether it is considered a delivering or non-delivering recipe. A delivering recipe contains an action that writes the message to a file, sends the message to another program, or forwards the message to another email address. A non-delivering recipe covers any other actions, such as a nesting block. A nesting block is a set of actions, contained in braces { }, that are performed on messages which match the recipe's conditions. Nesting blocks can be nested inside one another, providing greater control for identifying and performing actions on messages. When messages match a delivering recipe, Procmail performs the specified action and stops comparing the message against any other recipes. Messages that match non-delivering recipes continue to be compared against other recipes. 1 2 .4 .2 .2 . Flags Flags are essential to determine how or if a recipe's conditions are compared to a message. The eg rep utility is used internally for matching of the conditions. The following flags are commonly used: A — Specifies that this recipe is only used if the previous recipe without an A or a flag also matched this message. a — Specifies that this recipe is only used if the previous recipe with an A or a flag also matched this message and was successfully completed. B — Parses the body of the message and looks for matching conditions. b — Uses the body in any resulting action, such as writing the message to a file or forwarding it. This is the default behavior. 183 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide c — Generates a carbon copy of the email. This is useful with delivering recipes, since the required action can be performed on the message and a copy of the message can continue being processed in the rc files. D — Makes the eg rep comparison case-sensitive. By default, the comparison process is not case-sensitive. E — While similar to the A flag, the conditions in the recipe are only compared to the message if the immediately preceding recipe without an E flag did not match. This is comparable to an else action. e — The recipe is compared to the message only if the action specified in the immediately preceding recipe fails. f — Uses the pipe as a filter. H — Parses the header of the message and looks for matching conditions. This is the default behavior. h — Uses the header in a resulting action. This is the default behavior. w — Tells Procmail to wait for the specified filter or program to finish, and reports whether or not it was successful before considering the message filtered. W — Is identical to w except that " Program failure" messages are suppressed. For a detailed list of additional flags, see the pro cmai l rc man page. 1 2 .4 .2 .3. Spe cifying a Lo cal Lo ckfile Lockfiles are very useful with Procmail to ensure that more than one process does not try to alter a message simultaneously. Specify a local lockfile by placing a colon (: ) after any flags on a recipe's first line. This creates a local lockfile based on the destination file name plus whatever has been set in the LO C KEXT global environment variable. Alternatively, specify the name of the local lockfile to be used with this recipe after the colon. 1 2 .4 .2 .4 . Spe cial Co ndit io ns and Act io ns Special characters used before Procmail recipe conditions and actions change the way they are interpreted. The following characters may be used after the asterisk character (*) at the beginning of a recipe's condition line: ! — In the condition line, this character inverts the condition, causing a match to occur only if the condition does not match the message. < — Checks if the message is under a specified number of bytes. > — Checks if the message is over a specified number of bytes. The following characters are used to perform special actions: ! — In the action line, this character tells Procmail to forward the message to the specified email addresses. $ — Refers to a variable set earlier in the rc file. This is often used to set a common mailbox that is referred to by various recipes. 184 Chapt er 1 2 . Mail Servers | — Starts a specified program to process the message. { and } — Constructs a nesting block, used to contain additional recipes to apply to matching messages. If no special character is used at the beginning of the action line, Procmail assumes that the action line is specifying the mailbox in which to write the message. 1 2 .4 .2 .5 . Re cipe Exam ple s Procmail is an extremely flexible program, but as a result of this flexibility, composing Procmail recipes from scratch can be difficult for new users. The best way to develop the skills to build Procmail recipe conditions stems from a strong understanding of regular expressions combined with looking at many examples built by others. A thorough explanation of regular expressions is beyond the scope of this section. The structure of Procmail recipes and useful sample Procmail recipes can be found at various places on the Internet. The proper use and adaptation of regular expressions can be derived by viewing these recipe examples. In addition, introductory information about basic regular expression rules can be found in the g rep(1) man page. The following simple examples demonstrate the basic structure of Procmail recipes and can provide the foundation for more intricate constructions. A basic recipe may not even contain conditions, as is illustrated in the following example: :0: new-mail.spool The first line specifies that a local lockfile is to be created but does not specify a name, so Procmail uses the destination file name and appends the value specified in the LO C KEXT environment variable. No condition is specified, so every message matches this recipe and is placed in the single spool file called new-mai l . spo o l , located within the directory specified by the MAILD IR environment variable. An MUA can then view messages in this file. A basic recipe, such as this, can be placed at the end of all rc files to direct messages to a default location. The following example matched messages from a specific email address and throws them away. :0 * ^From: spammer@ domain.com /dev/null With this example, any messages sent by spammer@ d o mai n. co m are sent to the /d ev/nul l device, deleting them. 185 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Warning Be certain that rules are working as intended before sending messages to /d ev/nul l for permanent deletion. If a recipe inadvertently catches unintended messages, and those messages disappear, it becomes difficult to troubleshoot the rule. A better solution is to point the recipe's action to a special mailbox, which can be checked from time to time to look for false positives. Once satisfied that no messages are accidentally being matched, delete the mailbox and direct the action to send the messages to /d ev/nul l . The following recipe grabs email sent from a particular mailing list and places it in a specified folder. :0: * ^(From|Cc|To).*tux-lug tuxlug Any messages sent from the tux-l ug @ d o mai n. co m mailing list are placed in the tuxl ug mailbox automatically for the MUA. Note that the condition in this example matches the message if it has the mailing list's email address on the Fro m, C c, or T o lines. Consult the many Procmail online resources available in Section 12.6, “ Additional Resources” for more detailed and powerful recipes. 1 2 .4 .2 .6 . Spam Filt e rs Because it is called by Sendmail, Postfix, and Fetchmail upon receiving new emails, Procmail can be used as a powerful tool for combating spam. This is particularly true when Procmail is used in conjunction with SpamAssassin. When used together, these two applications can quickly identify spam emails, and sort or destroy them. SpamAssassin uses header analysis, text analysis, blacklists, a spam-tracking database, and selflearning Bayesian spam analysis to quickly and accurately identify and tag spam. Note In order to use Sp amAssassin , first ensure the spamassassin package is installed on your system by running, as ro o t: ~]# yum i nstal l spamassassi n For more information on installing packages with Yum, see Section 7.2.4, “ Installing Packages” . The easiest way for a local user to use SpamAssassin is to place the following line near the top of the ~ /. pro cmai l rc file: INC LUD ER C = /etc/mai l /spamassassi n/spamassassi n-d efaul t. rc 186 Chapt er 1 2 . Mail Servers The /etc/mai l /spamassassi n/spamassassi n-d efaul t. rc contains a simple Procmail rule that activates SpamAssassin for all incoming email. If an email is determined to be spam, it is tagged in the header as such and the title is prepended with the following pattern: *****SPAM***** The message body of the email is also prepended with a running tally of what elements caused it to be diagnosed as spam. To file email tagged as spam, a rule similar to the following can be used: : 0 Hw * ^X-Spam-Status: Y es spam This rule files all email tagged in the header as spam into a mailbox called spam. Since SpamAssassin is a Perl script, it may be necessary on busy servers to use the binary SpamAssassin daemon (spamd ) and the client application (sp amc). Configuring SpamAssassin this way, however, requires ro o t access to the host. To start the spamd daemon, type the following command: ~]# systemctl start spamassassi n To start the SpamAssassin daemon when the system is booted, run: systemctl enabl e spamassassi n. servi ce See Chapter 8, Managing Services with systemd for more information about starting and stopping services. To configure Procmail to use the SpamAssassin client application instead of the Perl script, place the following line near the top of the ~ /. pro cmai l rc file. For a system-wide configuration, place it in /etc/pro cmai l rc: INC LUD ER C = /etc/mai l /spamassassi n/spamassassi n-spamc. rc 12.5. Mail User Agent s Red Hat Enterprise Linux offers a variety of email programs, both, graphical email client programs, such as Evo lu t io n , and text-based email programs such as mutt. The remainder of this section focuses on securing communication between a client and a server. 12.5.1. Securing Communicat ion Popular MUAs included with Red Hat Enterprise Linux, such as Evo lu t io n and Mu t t offer SSLencrypted email sessions. Like any other service that flows over a network unencrypted, important email information, such as user names, passwords, and entire messages, may be intercepted and viewed by users on the network. Additionally, since the standard P O P and IMAP protocols pass authentication information unencrypted, it is possible for an attacker to gain access to user accounts by collecting user names and passwords as they are passed over the network. 187 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 1 2 .5 .1 .1 . Se cure Em ail Clie nt s Most Linux MUAs designed to check email on remote servers support SSL encryption. To use SSL when retrieving email, it must be enabled on both the email client and the server. SSL is easy to enable on the client-side, often done with the click of a button in the MUA's configuration window or via an option in the MUA's configuration file. Secure IMAP and P O P have known port numbers (9 9 3 and 9 9 5, respectively) that the MUA uses to authenticate and download messages. 1 2 .5 .1 .2 . Se curing Em ail Clie nt Co m m unicat io ns Offering SSL encryption to IMAP and P O P users on the email server is a simple matter. First, create an SSL certificate. This can be done in two ways: by applying to a Certificate Authority (CA) for an SSL certificate or by creating a self-signed certificate. Warning Self-signed certificates should be used for testing purposes only. Any server used in a production environment should use an SSL certificate signed by a CA. To create a self-signed SSL certificate for IMAP or P O P , change to the /etc/pki /d o veco t/ directory, edit the certificate parameters in the /etc/pki /d o veco t/d o veco t-o penssl . cnf configuration file as you prefer, and type the following commands, as ro o t: dovecot]# rm -f certs/d o veco t. pem pri vate/d o veco t. pem dovecot]# /usr/l i bexec/d o veco t/mkcert. sh Once finished, make sure you have the following configurations in your /etc/d o veco t/co nf. d /10 -ssl . co nf file: ssl_cert = prompt, you have successfully logged in. Once you are logged in, type hel p for a list of commands. If you want to browse the contents of your home directory, replace sharename with your username. If the -U switch is not used, the username of the current user is passed to the Samba server. To exit smbcl i ent, type exi t at the smb: \> prompt. 1 4 .1 .3.2 . Mo unt ing t he Share 212 Chapt er 1 4 . File and Print Servers 1 4 .1 .3.2 . Mo unt ing t he Share Sometimes it is useful to mount a Samba share to a directory so that the files in the directory can be treated as if they are part of the local file system. To mount a Samba share to a directory, create a directory to mount it to (if it does not already exist), and execute the following command as ro o t: ~]# mo unt -t ci fs //servername/sharename /mnt/point/ -o username= username,passwo rd = password This command mounts sharename from servername in the local directory /mnt/point/. Note The mo u n t .cif s utility is a separate RPM (independent from Samba). In order to use mo u n t .cif s, first ensure the cifs-utils package is installed on your system by running, as ro o t: ~]# yum i nstal l ci fs-uti l s For more information on installing packages with Yum, see Section 7.2.4, “ Installing Packages” . Note that the cifs-utils package also contains the cif s.u p call binary called by the kernel in order to perform kerberized CIFS mounts. For more information on cif s.u p call, see man ci fs. upcal l . For more information about mounting a samba share, see man mo unt. ci fs. Warning Some CIFS servers require plain text passwords for authentication. Support for plain text password authentication can be enabled using the following command as ro o t: ~]# echo 0 x37 > /pro c/fs/ci fs/Securi tyFl ag s WARNING: This operation can expose passwords by removing password encryption. 14 .1.4 . Configuring a Samba Server The default configuration file (/etc/samba/smb. co nf) allows users to view their home directories as a Samba share. It also shares all printers configured for the system as Samba shared printers. You can attach a printer to the system and print to it from the Windows machines on your network. 1 4 .1 .4 .1 . Graphical Co nfigurat io n To configure Samba using a graphical interface, use one of the available Samba graphical user interfaces. A list of available GUIs can be found at http://www.samba.org/samba/GUI/. 213 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 1 4 .1 .4 .2 . Co m m and Line Co nfigurat io n Samba uses /etc/samba/smb. co nf as its configuration file. If you change this configuration file, the changes do not take effect until you restart the Samba daemon with the following command, as ro o t: ~]# systemctl restart smb. servi ce To specify the Windows workgroup and a brief description of the Samba server, edit the following lines in your /etc/samba/smb. co nf file: workgroup = WORKGROUPNAME server string = BRIEF COMMENT ABOUT SERVER Replace WORKGROUPNAME with the name of the Windows workgroup to which this machine should belong. The BRIEF COMMENT ABOUT SERVER is optional and is used as the Windows comment about the Samba system. To create a Samba share directory on your Linux system, add the following section to your /etc/samba/smb. co nf file (after modifying it to reflect your needs and your system): [sharename] comment = Insert a comment here path = /home/share/ valid users = tfox carole public = no writable = yes printable = no create mask = 0765 The above example allows the users tfo x and caro l e to read and write to the directory /ho me/share, on the Samba server, from a Samba client. 1 4 .1 .4 .3. Encrypt e d Passwo rds Encrypted passwords are enabled by default because it is more secure to use them. To create a user with an encrypted password, use the command smbpasswd -a username. 14 .1.5. St art ing and St opping Samba To start a Samba server, type the following command in a shell prompt, as ro o t: ~]# systemctl start smb. servi ce Important To set up a domain member server, you must first join the domain or Active D irectory using the net jo i n command before starting the smb service. Also, it is recommended to run wi nbi nd before smbd . To stop the server, type the following command in a shell prompt, as ro o t: 214 Chapt er 1 4 . File and Print Servers ~]# systemctl sto p smb. servi ce The restart option is a quick way of stopping and then starting Samba. This is the most reliable way to make configuration changes take effect after editing the configuration file for Samba. Note that the restart option starts the daemon even if it was not running originally. To restart the server, type the following command in a shell prompt, as ro o t: ~]# systemctl restart smb. servi ce The co nd restart (conditional restart) option only starts smb on the condition that it is currently running. This option is useful for scripts, because it does not start the daemon if it is not running. Note When the /etc/samba/smb. co nf file is changed, Samba automatically reloads it after a few minutes. Issuing a manual restart or rel o ad is just as effective. To conditionally restart the server, type the following command, as ro o t: ~]# systemctl try-restart smb. servi ce A manual reload of the /etc/samba/smb. co nf file can be useful in case of a failed automatic reload by the smb service. To ensure that the Samba server configuration file is reloaded without restarting the service, type the following command, as ro o t: ~]# systemctl rel o ad smb. servi ce By default, the smb service does not start automatically at boot time. To configure Samba to start at boot time, type the following at a shell prompt as ro o t: ~]# systemctl enabl e smb. servi ce See Chapter 8, Managing Services with systemd for more information regarding this tool. 14 .1.6. Samba Net work Browsing Network browsing enables Windows and Samba servers to appear in the Windows Netwo rk Nei g hbo rho o d . Inside the Netwo rk Nei g hbo rho o d , icons are represented as servers and if opened, the server's shares and printers that are available are displayed. Network browsing capabilities require NetBIOS over T C P /IP . NetBIOS-based networking uses broadcast (UD P ) messaging to accomplish browse list management. Without NetBIOS and WINS as the primary method for T C P /IP hostname resolution, other methods such as static files (/etc/ho sts) or D NS, must be used. A domain master browser collates the browse lists from local master browsers on all subnets so that browsing can occur between workgroups and subnets. Also, the domain master browser should preferably be the local master browser for its own subnet. 1 4 .1 .6 .1 . Do m ain Bro wsing 215 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide By default, a Windows server PD C for a domain is also the domain master browser for that domain. A Samba server must not be set up as a domain master server in this type of situation. For subnets that do not include the Windows server PD C, a Samba server can be implemented as a local master browser. Configuring the /etc/samba/smb. co nf file for a local master browser (or no browsing at all) in a domain controller environment is the same as workgroup configuration (see Section 14.1.4, “ Configuring a Samba Server” ). 1 4 .1 .6 .2 . WINS (Windo ws Int e rne t Nam e Se rve r) Either a Samba server or a Windows NT server can function as a WINS server. When a WINS server is used with NetBIOS enabled, UD P unicasts can be routed which allows name resolution across networks. Without a WINS server, the UD P broadcast is limited to the local subnet and therefore cannot be routed to other subnets, workgroups, or domains. If WINS replication is necessary, do not use Samba as your primary WINS server, as Samba does not currently support WINS replication. In a mixed NT/2000/2003/2008 server and Samba environment, it is recommended that you use the Microsoft WINS capabilities. In a Samba-only environment, it is recommended that you use only one Samba server for WINS. The following is an example of the /etc/samba/smb. co nf file in which the Samba server is serving as a WINS server: [global] wins support = Yes Note All servers (including Samba) should connect to a WINS server to resolve NetBIOS names. Without WINS, browsing only occurs on the local subnet. Furthermore, even if a domain-wide list is somehow obtained, hosts cannot be resolved for the client without WINS. 14 .1.7. Samba Dist ribut ion Programs net net protocol function misc_options target_options The net utility is similar to the net utility used for Windows and MS-D OS. The first argument is used to specify the protocol to use when executing a command. The protocol option can be ad s, rap, or rpc for specifying the type of server connection. Active D irectory uses ad s, Win9x/NT3 uses rap, and Windows NT4/2000/2003/2008 uses rpc. If the protocol is omitted, net automatically tries to determine it. The following example displays a list of the available shares for a host named wakko : ~ ]$ net -l share -S wakko Password: Enumerating shared resources (exports) on remote server: Share name Type Description ----------------------- 216 Chapt er 1 4 . File and Print Servers data tmp IPC$ ADMIN$ Disk Disk IPC IPC Wakko data share Wakko tmp share IPC Service (Samba Server) IPC Service (Samba Server) The following example displays a list of Samba users for a host named wakko : ~ ]$ net -l user -S wakko root password: User name Comment ----------------------------andriusb Documentation joe Marketing lisa Sales nmbl o o kup nmbl o o kup options netbios_name The nmbl o o kup program resolves NetBIOS names into IP addresses. The program broadcasts its query on the local subnet until the target machine replies. The following example displays the IP address of the NetBIOS name trek: ~ ]$ nmbl o o kup trek querying trek on 10.1.59.255 10.1.56.45 trek<00> pd bed i t pd bed i t options The pd bed i t program manages accounts located in the SAM database. All back ends are supported including smbpasswd , LD AP, and the td b database library. The following are examples of adding, deleting, and listing users: ~]$ pd bed i t -a kri sti n new password: retype new password: Unix username: kristin NT username: Account Flags: [U ] User SID: S-1-5-21-1210235352-3804200048-1474496110-2012 Primary Group SID: S-1-5-21-1210235352-3804200048-1474496110-2077 Full Name: Home Directory: \\wakko\kristin HomeDir Drive: Logon Script: Profile Path: \\wakko\kristin\profile Domain: WAKKO Account desc: Workstations: Munged dial: Logon time: 0 Logoff time: Mon, 18 Jan 2038 22:14:07 GMT Kickoff time: Mon, 18 Jan 2038 22:14:07 GMT 217 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Password last set: Thu, 29 Jan 2004 08:29:28 GMT Password can change: Thu, 29 Jan 2004 08:29:28 GMT Password must change: Mon, 18 Jan 2038 22:14:07 GMT ~ ]$ pd bed i t -v -L kri sti n Unix username: kristin NT username: Account Flags: [U ] User SID: S-1-5-21-1210235352-3804200048-1474496110-2012 Primary Group SID: S-1-5-21-1210235352-3804200048-1474496110-2077 Full Name: Home Directory: \\wakko\kristin HomeDir Drive: Logon Script: Profile Path: \\wakko\kristin\profile Domain: WAKKO Account desc: Workstations: Munged dial: Logon time: 0 Logoff time: Mon, 18 Jan 2038 22:14:07 GMT Kickoff time: Mon, 18 Jan 2038 22:14:07 GMT Password last set: Thu, 29 Jan 2004 08:29:28 GMT Password can change: Thu, 29 Jan 2004 08:29:28 GMT Password must change: Mon, 18 Jan 2038 22:14:07 GMT ~ ]$ pd bed i t -L andriusb:505: joe:503: lisa:504: kristin:506: ~ ]$ pd bed i t -x jo e ~ ]$ pd bed i t -L andriusb:505: lisa:504: kristin:506: rpccl i ent rpccl i ent server options The rpccl i ent program issues administrative commands using Microsoft RPCs, which provide access to the Windows administration graphical user interfaces (GUIs) for systems management. This is most often used by advanced users that understand the full complexity of Microsoft RPCs. smbcacl s smbcacl s //server/share filename options The smbcacl s program modifies Windows ACLs on files and directories shared by a Samba server or a Windows server. smbcl i ent smbcl i ent //server/share password options The smbcl i ent program is a versatile UNIX client which provides functionality similar to ftp. smbco ntro l smbco ntro l -i options 218 Chapt er 1 4 . File and Print Servers smbco ntro l options destination messagetype parameters The smbco ntro l program sends control messages to running smbd , nmbd , or wi nbi nd d daemons. Executing smbco ntro l -i runs commands interactively until a blank line or a 'q' is entered. smbpasswd smbpasswd options username password The smbpasswd program manages encrypted passwords. This program can be run by a superuser to change any user's password and also by an ordinary user to change their own Samba password. smbspo o l smbspo o l job user title copies options filename The smbspo o l program is a CUPS-compatible printing interface to Samba. Although designed for use with CUPS printers, smbspo o l can work with non-CUPS printers as well. smbstatus smbstatus options The smbstatus program displays the status of current connections to a Samba server. smbtar smbtar options The smbtar program performs backup and restores of Windows-based share files and directories to a local tape archive. Though similar to the tar command, the two are not compatible. testparm testparm options filename hostname IP_address The testparm program checks the syntax of the /etc/samba/smb. co nf file. If your smb. co nf file is in the default location (/etc/samba/smb. co nf) you do not need to specify the location. Specifying the host name and IP address to the testparm program verifies that the ho sts. al l o w and ho st. d eny files are configured correctly. The testparm program also displays a summary of your /etc/samba/smb. co nf file, and the server's role, after testing. This is convenient when debugging as it excludes comments and concisely presents information for experienced administrators to read. For example: ~ ]$ testparm Load smb config files from /etc/samba/smb.conf Processing section "[homes]" Processing section "[printers]" Processing section "[tmp]" Processing section "[html]" Loaded services file OK. Server role: ROLE_STANDALONE Press enter to see a dump of your service definitions # Global parameters 219 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide [global] workgroup = MYGROUP server string = Samba Server security = SHARE log file = /var/log/samba/%m.log max log size = 50 socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192 dns proxy = No [homes] comment = Home Directories read only = No browseable = No [printers] comment = All Printers path = /var/spool/samba printable = Yes browseable = No [tmp] comment = Wakko tmp path = /tmp guest only = Yes [html] comment = Wakko www path = /var/www/html force user = andriusb force group = users read only = No guest only = Yes wbi nfo wbi nfo options The wbi nfo program displays information from the wi nbi nd d daemon. The wi nbi nd d daemon must be running for wbi nfo to work. 14 .1.8. Addit ional Resources The following sections give you the means to explore Samba in greater detail. 1 4 .1 .8 .1 . Inst alle d Do cum e nt at io n /usr/share/d o c/samba-version-number/ — All additional files included with the Samba distribution. This includes all helper scripts, sample configuration files, and documentation. See the following manual pages for detailed information about Samb a: smb. co nf samba smbd nmbd wi nbi nd 220 Chapt er 1 4 . File and Print Servers 1 4 .1 .8 .2 . Use ful We bsit e s http://www.samba.org/ — Homepage for the Samba distribution and all official documentation created by the Samba development team. Many resources are available in HTML and PD F formats, while others are only available for purchase. Although many of these links are not Red Hat Enterprise Linux specific, some concepts may apply. http://samba.org/samba/archives.html — Active email lists for the Samba community. Enabling digest mode is recommended due to high levels of list activity. Samba newsgroups — Samba threaded newsgroups, such as www.gmane.org, that use the NNT P protocol are also available. This an alternative to receiving mailing list emails. 14 .2. FT P The File Transfer Protocol (FT P ) is one of the oldest and most commonly used protocols found on the Internet today. Its purpose is to reliably transfer files between computer hosts on a network without requiring the user to log directly in to the remote host or to have knowledge of how to use the remote system. It allows users to access files on remote systems using a standard set of simple commands. This section outlines the basics of the FT P protocol and introduces vsftpd, which is the preferred FT P server in Red Hat Enterprise Linux. 14 .2.1. T he File T ransfer Prot ocol FTP uses a client-server architecture to transfer files using the T C P network protocol. Because FT P is a rather old protocol, it uses unencrypted user name and password authentication. For this reason, it is considered an insecure protocol and should not be used unless absolutely necessary. However, because FT P is so prevalent on the Internet, it is often required for sharing files to the public. System administrators, therefore, should be aware of FT P 's unique characteristics. This section describes how to configure vsf t p d to establish connections secured by T LS and how to secure an FT P server with the help of SELin u x. A good substitute for FT P is sf t p from the O p en SSH suite of tools. For information about configuring O p en SSH and about the SSH protocol in general, refer to Chapter 9, OpenSSH. Unlike most protocols used on the Internet, FT P requires multiple network ports to work properly. When an FT P client application initiates a connection to an FT P server, it opens port 21 on the server — known as the command port. This port is used to issue all commands to the server. Any data requested from the server is returned to the client via a data port. The port number for data connections, and the way in which data connections are initialized, vary depending upon whether the client requests the data in active or passive mode. The following defines these modes: act ive mo d e Active mode is the original method used by the FT P protocol for transferring data to the client application. When an active-mode data transfer is initiated by the FT P client, the server opens a connection from port 20 on the server to the IP address and a random, unprivileged port (greater than 10 24 ) specified by the client. This arrangement means that the client machine must be allowed to accept connections over any port above 10 24 . With the growth of insecure networks, such as the Internet, the use of firewalls for protecting client machines is now prevalent. Because these client-side firewalls often deny incoming connections from active-mode FT P servers, passive mode was devised. p assive mo d e 221 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Passive mode, like active mode, is initiated by the FT P client application. When requesting data from the server, the FT P client indicates it wants to access the data in passive mode and the server provides the IP address and a random, unprivileged port (greater than 10 24 ) on the server. The client then connects to that port on the server to download the requested information. While passive mode does resolve issues for client-side firewall interference with data connections, it can complicate administration of the server-side firewall. You can reduce the number of open ports on a server by limiting the range of unprivileged ports on the FT P server. This also simplifies the process of configuring firewall rules for the server. 14 .2.2. T he vsft pd Server The Very Secure FTP Daemon (vsftpd ) is designed from the ground up to be fast, stable, and, most importantly, secure. vsftpd is the only stand-alone FT P server distributed with Red Hat Enterprise Linux, due to its ability to handle large numbers of connections efficiently and securely. The security model used by vsftpd has three primary aspects: Strong separation of privileged and non-privileged processes — Separate processes handle different tasks, and each of these processes runs with the minimal privileges required for the task. Tasks requiring elevated privileges are handled by processes with the minimal privilege necessary — By taking advantage of compatibilities found in the l i bcap library, tasks that usually require full root privileges can be executed more safely from a less privileged process. Most processes run in a chroot jail — Whenever possible, processes are change-rooted to the directory being shared; this directory is then considered a chro o t jail. For example, if the /var/ftp/ directory is the primary shared directory, vsftpd reassigns /var/ftp/ to the new root directory, known as /. This disallows any potential malicious hacker activities for any directories not contained in the new root directory. Use of these security practices has the following effect on how vsftpd deals with requests: The parent process runs with the least privileges required — The parent process dynamically calculates the level of privileges it requires to minimize the level of risk. Child processes handle direct interaction with the FT P clients and run with as close to no privileges as possible. All operations requiring elevated privileges are handled by a small parent process — Much like the Ap ach e HT T P Server, vsftpd launches unprivileged child processes to handle incoming connections. This allows the privileged, parent process to be as small as possible and handle relatively few tasks. All requests from unprivileged child processes are distrusted by the parent process — Communication with child processes is received over a socket, and the validity of any information from child processes is checked before being acted on. Most interactions with FTP clients are handled by unprivileged child processes in a chroot jail — Because these child processes are unprivileged and only have access to the directory being shared, any crashed processes only allow the attacker access to the shared files. 1 4 .2 .2 .1 . St art ing and St o pping vsft pd To start the vsftpd service in the current session, type the following at a shell prompt as ro o t: ~]# systemctl start vsftpd . servi ce 222 Chapt er 1 4 . File and Print Servers To stop the service in the current session, type as ro o t: ~]# systemctl sto p vsftpd . servi ce To restart the vsftpd service, run the following command as ro o t: ~]# systemctl restart vsftpd . servi ce This command stops and immediately starts the vsftpd service, which is the most efficient way to make configuration changes take effect after editing the configuration file for this FT P server. Alternatively, you can use the following command to restart the vsftpd service only if it is already running: ~]# systemctl try-restart vsftpd . servi ce By default, the vsftpd service does not start automatically at boot time. To configure the vsftpd service to start at boot time, type the following at a shell prompt as ro o t: ~]# systemctl enabl e vsftpd . servi ce ln -s '/usr/lib/systemd/system/vsftpd.service' '/etc/systemd/system/multiuser.target.wants/vsftpd.service' For more information on how to manage system services in Red Hat Enterprise Linux 7, see Chapter 8, Managing Services with systemd. 1 4 .2 .2 .2 . St art ing Mult iple Co pie s o f vsft pd Sometimes, one computer is used to serve multiple FT P domains. This is a technique called multihoming. One way to multihome using vsftpd is by running multiple copies of the daemon, each with its own configuration file. To do this, first assign all relevant IP addresses to network devices or alias network devices on the system. For more information about configuring network devices, device aliases, and additional information about network configuration scripts, see the Red Hat Enterprise Linux 7 Networking Guide. Next, the DNS server for the FT P domains must be configured to reference the correct machine. For information about B IN D , the D NS protocol implementation used in Red Hat Enterprise Linux, and its configuration files, see the Red Hat Enterprise Linux 7 Networking Guide. For vsftpd to answer requests on different IP addresses, multiple copies of the daemon must be running. To facilitate launching multiple instances of the vsftpd daemon, a special systemd service unit (vsftpd @ . servi ce) for launching vsftpd as an instantiated service is supplied in the vsftpd package. In order to make use of this service unit, a separate vsftpd configuration file for each required instance of the FT P server must be created and placed in the /etc/vsftpd / directory. Note that each of these configuration files must have a unique name (such as /etc/vsftpd /vsftpd-site2. co nf) and must be readable and writable only by the ro o t user. Within each configuration file for each FT P server listening on an IP v4 network, the following directive must be unique: l i sten_ad d ress= N.N.N.N 223 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Replace N.N.N.N with a unique IP address for the FT P site being served. If the site is using IP v6 , use the l i sten_ad d ress6 directive instead. Once there are multiple configuration files present in the /etc/vsftpd / directory, individual instances of the vsftpd daemon can be started by executing the following command as ro o t: ~]# systemctl start vsftpd @ configuration-file-name. servi ce In the above command, replace configuration-file-name with the unique name of the requested server's configuration file, such as vsftpd -si te-2. Note that the configuration file's . co nf extension should not be included in the command. If you want to start several instances of the vsftpd daemon at once, you can make use of a systemd target unit file (vsftpd . targ et), which is supplied in the vsftpd package. This systemd target causes an independent vsftpd daemon to be launched for each available vsftpd configuration file in the /etc/vsftpd / directory. Execute the following command as ro o t to enable the target: ~]# systemctl enabl e vsftpd . targ et ln -s '/usr/lib/systemd/system/vsftpd.target' '/etc/systemd/system/multiuser.target.wants/vsftpd.target' The above command configures the systemd service manager to launch the vsftpd service (along with the configured vsftpd server instances) at boot time. To start the service immediately, without rebooting the system, execute the following command as ro o t: ~]# systemctl start vsftpd . targ et See Section 8.3, “ Working with systemd Targets” for more information on how to use systemd targets to manage services. Other directives to consider altering on a per-server basis are: ano n_ro o t l o cal _ro o t vsftpd _l o g _fi l e xferl o g _fi l e 1 4 .2 .2 .3. Encrypt ing vsft pd Co nne ct io ns Using T LS In order to counter the inherently insecure nature of FT P , which transmits user names, passwords, and data without encryption by default, the vsftpd daemon can be configured to utilize the T LS protocol to authenticate connections and encrypt all transfers. Note that an FT P client that supports T LS is needed to communicate with vsftpd with T LS enabled. 224 Chapt er 1 4 . File and Print Servers Note SSL (Secure Sockets Layer) is the name of an older implementation of the security protocol. The new versions are called T LS (Transport Layer Security). Only the newer versions (T LS) should be used as SSL suffers from serious security vulnerabilities. The documentation included with the vsf t p d server, as well as the configuration directives used in the vsftpd . co nf file, use the SSL name when referring to security-related matters, but T LS is supported and used by default when the ssl _enabl e directive is set to Y ES. Set the ssl _enabl e configuration directive in the vsftpd . co nf file to Y ES to turn on T LS support. The default settings of other T LS-related directives that become automatically active when the ssl _enabl e option is enabled provide for a reasonably well-configured T LS set up. This includes, among other things, the requirement to only use the T LS v1 protocol for all connections (the use of the insecure SSL protocol versions is disabled by default) or forcing all non-anonymous logins to use T LS for sending passwords and data transfers. Examp le 14 .1. C o n f ig u rin g vsf t p d t o U se T LS In this example, the configuration directives explicitly disable the older SSL versions of the security protocol in the vsftpd . co nf file: ssl_enable=YES ssl_tlsv1=YES ssl_sslv2=NO ssl_sslv3=NO Restart the vsftpd service after you modify its configuration: ~]# systemctl restart vsftpd . servi ce See the vsftpd.conf(5) manual page for other T LS-related configuration directives for fine-tuning the use of T LS by vsftpd . 1 4 .2 .2 .4 . SELinux Po licy fo r vsft pd The SELinux policy governing the vsftpd daemon (as well as other ftpd processes), defines a mandatory access control, which, by default, is based on least access required. In order to allow the FT P daemon to access specific files or directories, appropriate labels need to be assigned to them. For example, in order to be able to share files anonymously, the publ i c_co ntent_t label must be assigned to the files and directories to be shared. You can do this using the chco n command as ro o t: ~]# chco n -R -t publ i c_co ntent_t /path/to/directory In the above command, replace /path/to/directory with the path to the directory to which you want to assign the label. Similarly, if you want to set up a directory for uploading files, you need to assign that particular directory the publ i c_co ntent_rw_t label. In addition to that, the al l o w_ftpd _ano n_wri te SELinux Boolean option must be set to 1. Use the setsebo o l command as ro o t to do that: 225 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# setsebo o l -P al l o w_ftpd _ano n_wri te= 1 If you want local users to be able to access their home directories through FT P , which is the default setting on Red Hat Enterprise Linux 7, the ftp_ho me_d i r Boolean option needs to be set to 1. If vsftpd is to be allowed to run in standalone mode, which is also enabled by default on Red Hat Enterprise Linux 7, the ftpd _i s_d aemo n option needs to be set to 1 as well. See the ftpd_selinux(8) manual page for more information, including examples of other useful labels and Boolean options, on how to configure the SELinux policy pertaining to FT P . Also, see the Red Hat Enterprise Linux 7 SELinux User's and Administrator's Guide for more detailed information about SELinux in general. 14 .2.3. Addit ional Resources For more information about vsftpd , see the following resources. 1 4 .2 .3.1 . Inst alle d Do cum e nt at io n The /usr/share/d o c/vsftpd -version-number/ directory — Replace version-number with the installed version of the vsftpd package. This directory contains a R EAD ME file with basic information about the software. The T UNING file contains basic performance-tuning tips and the SEC UR IT Y / directory contains information about the security model employed by vsftpd . vsftpd -related manual pages — There are a number of manual pages for the daemon and the configuration files. The following lists some of the more important manual pages. Server Ap p licat io n s vsftpd(8) — D escribes available command-line options for vsftpd . C o n f ig u rat io n Files vsftpd.conf(5) — Contains a detailed list of options available within the configuration file for vsftpd . hosts_access(5) — D escribes the format and options available within the T C P wrappers configuration files: ho sts. al l o w and ho sts. d eny. In t eract io n wit h SELin u x ftpd_selinux(8) — Contains a description of the SELinux policy governing ftpd processes as well as an explanation of the way SELinux labels need to be assigned and Booleans set. 1 4 .2 .3.2 . Online Do cum e nt at io n Ab o u t vsf t p d an d FT P in G en eral http://vsftpd.beasts.org/ — The vsftpd project page is a great place to locate the latest documentation and to contact the author of the software. http://slacksite.com/other/ftp.html — This website provides a concise explanation of the differences between active and passive-mode FT P . R ed H at En t erp rise Lin u x D o cu men t at io n Red Hat Enterprise Linux 7 Networking Guide — The Networking Guide for Red Hat Enterprise Linux 7 documents relevant information regarding the configuration and 226 Chapt er 1 4 . File and Print Servers administration of network interfaces, networks, and network services in this system. It provides an introduction to the ho stnamectl utility and explains how to use it to view and set host names on the command line, both locally and remotely. Red Hat Enterprise Linux 7 SELinux User's and Administrator's Guide — The SELinux User's and Administrator's Guide for Red Hat Enterprise Linux 7 describes the basic principles of SELin u x and documents in detail how to configure and use SELin u x with various services such as the Ap ach e H T T P Server, Po st f ix, Po st g reSQ L, or O p en Sh if t . It explains how to configure SELin u x access permissions for system services managed by systemd . Red Hat Enterprise Linux 7 Security Guide — The Security Guide for Red Hat Enterprise Linux 7 assists users and administrators in learning the processes and practices of securing their workstations and servers against local and remote intrusion, exploitation, and malicious activity. It also explains how to secure critical system services. R elevan t R FC D o cu men t s RFC 0959 — The original Request for Comments (RFC) of the FT P protocol from the IETF. RFC 1123 — The small FT P -related section extends and clarifies RFC 0959. RFC 2228 — FT P security extensions. vsf t p d implements the small subset needed to support TLS and SSL connections. RFC 2389 — Proposes FEAT and O P T S commands. RFC 2428 — IP v6 support. 14 .3. Print Set t ings The Prin t Set t in g s tool serves for printer configuring, maintenance of printer configuration files, print spool directories and print filters, and printer classes management. The tool is based on the Common Unix Printing System (CUPS). If you upgraded the system from a previous Red Hat Enterprise Linux version that used CUPS, the upgrade process preserved the configured printers. Important The cupsd . co nf man page documents configuration of a CUPS server. It includes directives for enabling SSL support. However, CUPS does not allow control of the protocol versions used. D ue to the vulnerability described in Resolution for POODLE SSLv3.0 vulnerability (CVE2014-3566) for components that do not allow SSLv3 to be disabled via configuration settings, Red Hat recommends that you do not rely on this for security. It is recommend that you use st u n n el to provide a secure tunnel and disable SSLv3. For more information on using st u n n el, see the Red Hat Enterprise Linux 7 Security Guide. For ad-hoc secure connections to a remote system's Prin t Set t in g s tool, use X11 forwarding over SSH as described in Section 9.4.1, “ X11 Forwarding” . 227 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note You can perform the same and additional operations on printers directly from the CUPS web application or command line. To access the application, in a web browser, go to http://localhost:631/. For CUPS manuals refer to the links on the Ho me tab of the web site. 14 .3.1. St art ing t he Print Set t ings Configurat ion T ool With the Prin t Set t in g s configuration tool you can perform various operations on existing printers and set up new printers. You can also use CUPS directly (go to http://localhost:631/ to access the CUPS web application). To start the Prin t Set t in g s tool from the command line, type system-co nfi g -pri nter at a shell prompt. The Prin t Set t in g s tool appears. Alternatively, if using the GNOME desktop, press the Super key to enter the Activities Overview, type P ri nt Setti ng s and then press Enter. The Prin t Set t in g s tool appears. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. The P ri nt Setti ng s window depicted in Figure 14.3, “ Print Settings window” appears. Fig u re 14 .3. Prin t Set t in g s win d o w 14 .3.2. St art ing Print er Set up Printer setup process varies depending on the printer queue type. If you are setting up a local printer connected with USB, the printer is discovered and added automatically. You will be prompted to confirm the packages to be installed and provide an administrator or the ro o t user password. Local printers connected with other port types and network printers need to be set up manually. 228 Chapt er 1 4 . File and Print Servers Follow this procedure to start a manual printer setup: 1. Start the Print Settings tool (refer to Section 14.3.1, “ Starting the Print Settings Configuration Tool” ). 2. Go to Server → N ew → Prin t er. 3. In the Authenti cate dialog box, enter an administrator or ro o t user password. If this is the first time you have configured a remote printer you will be prompted to authorize an adjustment to the firewall. 4. Select the printer connection type and provide its details in the area on the right. 14 .3.3. Adding a Local Print er Follow this procedure to add a local printer connected with other than a serial port: 1. Open the Ad d printer dialog (refer to Section 14.3.2, “ Starting Printer Setup” ). 2. If the device does not appear automatically, select the port to which the printer is connected in the list on the left (such as Seri al P o rt #1 or LP T #1). 3. On the right, enter the connection properties: f o r O ther UR I (for example file:/dev/lp0) f o r Seri al P o rt Baud Rate Parity D ata Bits Flow Control 229 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 14 .4 . Ad d in g a lo cal p rin t er 4. Click Fo rward . 5. Select the printer model. See Section 14.3.8, “ Selecting the Printer Model and Finishing” for details. 14 .3.4 . Adding an AppSocket /HP Jet Direct print er Follow this procedure to add an AppSocket/HP JetD irect printer: 1. Open the New P ri nter dialog (refer to Section 14.3.1, “ Starting the Print Settings Configuration Tool” ). 2. In the list on the left, select N et wo rk Prin t er → Ap p So cket /H P Jet D irect . 3. On the right, enter the connection settings: Ho stname Printer host name or IP address. P o rt Number Printer port listening for print jobs (9 10 0 by default). 230 Chapt er 1 4 . File and Print Servers Fig u re 14 .5. Ad d in g a Jet D irect p rin t er 4. Click Fo rward . 5. Select the printer model. See Section 14.3.8, “ Selecting the Printer Model and Finishing” for details. 14 .3.5. Adding an IPP Print er An IP P printer is a printer attached to a different system on the same TCP/IP network. The system this printer is attached to may either be running CUPS or simply configured to use IP P . If a firewall is enabled on the printer server, then the firewall must be configured to allow incoming T C P connections on port 6 31. Note that the CUPS browsing protocol allows client machines to discover shared CUPS queues automatically. To enable this, the firewall on the client machine must be configured to allow incoming UD P packets on port 6 31. Follow this procedure to add an IP P printer: 1. Open the New P ri nter dialog (refer to Section 14.3.2, “ Starting Printer Setup” ). 2. In the list of devices on the left, select N et wo rk Prin t er and In t ern et Prin t in g Pro t o co l ( ip p ) or In t ern et Prin t in g Pro t o co l ( h t t p s) . 3. On the right, enter the connection settings: 231 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Ho st The host name of the IP P printer. Q ueue The queue name to be given to the new queue (if the box is left empty, a name based on the device node will be used). Fig u re 14 .6 . Ad d in g an IPP p rin t er 4. Click Fo rward to continue. 5. Select the printer model. See Section 14.3.8, “ Selecting the Printer Model and Finishing” for details. 14 .3.6. Adding an LPD/LPR Host or Print er Follow this procedure to add an LPD /LPR host or printer: 1. Open the New P ri nter dialog (refer to Section 14.3.2, “ Starting Printer Setup” ). 2. In the list of devices on the left, select N et wo rk Prin t er → LPD /LPR H o st o r Prin t er. 3. On the right, enter the connection settings: Ho st 232 Chapt er 1 4 . File and Print Servers The host name of the LPD /LPR printer or host. Optionally, click P ro be to find queues on the LPD host. Q ueue The queue name to be given to the new queue (if the box is left empty, a name based on the device node will be used). Fig u re 14 .7. Ad d in g an LPD /LPR p rin t er 4. Click Fo rward to continue. 5. Select the printer model. See Section 14.3.8, “ Selecting the Printer Model and Finishing” for details. 14 .3.7. Adding a Samba (SMB) print er Follow this procedure to add a Samba printer: 233 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note Note that in order to add a Samba printer, you need to have the samba-client package installed. You can do so by running, as ro o t: yum i nstal l samba-cl i ent For more information on installing packages with Yum, refer to Section 7.2.4, “ Installing Packages” . 1. Open the New P ri nter dialog (refer to Section 14.3.2, “ Starting Printer Setup” ). 2. In the list on the left, select N et wo rk Prin t er → Win d o ws Prin t er via SAMB A. 3. Enter the SMB address in the smb: // field. Use the format computer name/printer share. In Figure 14.8, “ Adding a SMB printer” , the computer name is d el l bo x and the printer share is r2. Fig u re 14 .8. Ad d in g a SMB p rin t er 4. Click Bro wse to see the available workgroups/domains. To display only queues of a particular host, type in the host name (NetBios name) and click Bro wse. 5. Select either of the options: 234 Chapt er 1 4 . File and Print Servers A. P ro mpt user i f authenti cati o n i s req ui red : user name and password are collected from the user when printing a document. B. Set authenti cati o n d etai l s no w: provide authentication information now so it is not required later. In the Username field, enter the user name to access the printer. This user must exist on the SMB system, and the user must have permission to access the printer. The default user name is typically g uest for Windows servers, or no bo d y for Samba servers. 6. Enter the P asswo rd (if required) for the user specified in the Username field. Warning Samba printer user names and passwords are stored in the printer server as unencrypted files readable by ro o t and the Linux Printing D aemon, l pd . Thus, other users that have ro o t access to the printer server can view the user name and password you use to access the Samba printer. Therefore, when you choose a user name and password to access a Samba printer, it is advisable that you choose a password that is different from what you use to access your local Red Hat Enterprise Linux system. If there are files shared on the Samba print server, it is recommended that they also use a password different from what is used by the print queue. 7. Click Veri fy to test the connection. Upon successful verification, a dialog box appears confirming printer share accessibility. 8. Click Fo rward . 9. Select the printer model. See Section 14.3.8, “ Selecting the Printer Model and Finishing” for details. 14 .3.8. Select ing t he Print er Model and Finishing Once you have properly selected a printer connection type, the system attempts to acquire a driver. If the process fails, you can locate or search for the driver resources manually. Follow this procedure to provide the printer driver and finish the installation: 1. In the window displayed after the automatic driver detection has failed, select one of the following options: A. Sel ect a P ri nter fro m d atabase — the system chooses a driver based on the selected make of your printer from the list of Makes. If your printer model is not listed, choose G eneri c. B. P ro vi d e P P D fi l e — the system uses the provided PostScript Printer Description (PPD ) file for installation. A PPD file may also be delivered with your printer as being normally provided by the manufacturer. If the PPD file is available, you can choose this option and use the browser bar below the option description to select the PPD file. C. Search fo r a pri nter d ri ver to d o wnl o ad — enter the make and model of your printer into the Make and mo d el field to search on OpenPrinting.org for the appropriate packages. 235 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 14 .9 . Select in g a p rin t er b ran d 2. D epending on your previous choice provide details in the area displayed below: Printer brand for the Sel ect pri nter fro m d atabase option. PPD file location for the P ro vi d e P P D fi l e option. Printer make and model for the Search fo r a pri nter d ri ver to d o wnl o ad option. 3. Click Fo rward to continue. 4. If applicable for your option, window shown in Figure 14.10, “ Selecting a printer model” appears. Choose the corresponding model in the Mo d el s column on the left. Note On the right, the recommended printer driver is automatically selected; however, you can select another available driver. The print driver processes the data that you want to print into a format the printer can understand. Since a local printer is attached directly to your computer, you need a printer driver to process the data that is sent to the printer. 236 Chapt er 1 4 . File and Print Servers Fig u re 14 .10. Select in g a p rin t er mo d el 5. Click Fo rward . 6. Under the D escri be P ri nter enter a unique name for the printer in the P ri nter Name field. The printer name can contain letters, numbers, dashes (-), and underscores (_); it must not contain any spaces. You can also use the D escri pti o n and Lo cati o n fields to add further printer information. Both fields are optional, and may contain spaces. 237 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 14 .11. Prin t er set u p 7. Click Appl y to confirm your printer configuration and add the print queue if the settings are correct. Click Back to modify the printer configuration. 8. After the changes are applied, a dialog box appears allowing you to print a test page. Click Y es to print a test page now. Alternatively, you can print a test page later as described in Section 14.3.9, “ Printing a Test Page” . 14 .3.9. Print ing a T est Page After you have set up a printer or changed a printer configuration, print a test page to make sure the printer is functioning properly: 1. Right-click the printer in the P ri nti ng window and click Pro p ert ies. 2. In the Properties window, click Setti ng s on the left. 3. On the displayed Setti ng s tab, click the P ri nt T est P ag e button. 14 .3.10. Modifying Exist ing Print ers To delete an existing printer, in the P ri nt Setti ng s window, select the printer and go to Prin t er → D elet e. Confirm the printer deletion. Alternatively, press the D el ete key. To set the default printer, right-click the printer in the printer list and click the Set as D ef au lt button in the context menu. 238 Chapt er 1 4 . File and Print Servers 1 4 .3.1 0 .1 . T he Se t t ings Page To change printer driver configuration, double-click the corresponding name in the P ri nter list and click the Setti ng s label on the left to display the Setti ng s page. You can modify printer settings such as make and model, print a test page, change the device location (URI), and more. Fig u re 14 .12. Set t in g s p ag e 1 4 .3.1 0 .2 . T he Po licie s Page Click the P o l i ci es button on the left to change settings in printer state and print output. You can select the printer states, configure the Erro r P o l i cy of the printer (you can decide to abort the print job, retry, or stop it if an error occurs). You can also create a banner page (a page that describes aspects of the print job such as the originating printer, the user name from the which the job originated, and the security status of the document being printed): click the Starti ng Banner or End i ng Banner drop-down menu and choose the option that best describes the nature of the print jobs (for example, co nfi d enti al ). 14 .3.10.2.1. Sh arin g Prin t ers On the P o l i ci es page, you can mark a printer as shared: if a printer is shared, users published on the network can use it. To allow the sharing function for printers, go to Server → Set t in g s and select P ubl i sh shared pri nters co nnected to thi s system. 239 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 14 .13. Po licies p ag e Make sure that the firewall allows incoming T C P connections to port 6 31, the port for the Network Printing Server (IP P ) protocol. To allow IP P traffic through the firewall on Red Hat Enterprise Linux 7, make use of fi rewal l d 's IP P service. To do so, proceed as follows: Pro ced u re 14 .1. En ab lin g IPP Service in f irewalld 1. To start the graphical f irewall- co n f ig tool, press the Super key to enter the Activities Overview, type fi rewal l and then press Enter. The Fi rewal l C o nfi g urati o n window opens. You will be prompted for an administrator or ro o t password. Alternatively, to start the graphical firewall configuration tool using the command line, enter the following command as ro o t user: ~]# fi rewal l -co nfi g The Fi rewal l C o nfi g urati o n window opens. Look for the word “ Connected” in the lower left corner. This indicates that the f irewallco n f ig tool is connected to the user space daemon, fi rewal l d . To immediately change the current firewall settings, ensure the drop-down selection menu labeled C o nfi g urati o n is set to R u n t ime. Alternatively, to edit the settings to be applied at the next system start, or firewall reload, select Perman en t from the drop-down list. 2. Select the Zo nes tab and then select the firewall zone to correspond with the network interface to be used. The default is the p u b lic zone. The In t erf aces tab shows what interfaces have been assigned to a zone. 3. Select the Servi ces tab and then select the ip p service to enable sharing. The ip p - clien t service is required for accessing network printers. 24 0 Chapt er 1 4 . File and Print Servers 4. Close the f irewall- co n f ig tool. For more information on opening and closing ports in fi rewal l d , see the Red Hat Enterprise Linux 7 Security Guide. 14 .3.10.2.2. T h e Access C o n t ro l Pag e You can change user-level access to the configured printer on the Access C o ntro l page. Click the Access C o ntro l label on the left to display the page. Select either Al l o w pri nti ng fo r everyo ne except these users or D eny pri nti ng fo r everyo ne except these users and define the user set below: enter the user name in the text box and click the Ad d button to add the user to the user set. Fig u re 14 .14 . Access C o n t ro l p ag e 14 .3.10.2.3. T h e Prin t er O p t io n s Pag e The P ri nter O pti o ns page contains various configuration options for the printer media and output, and its content may vary from printer to printer. It contains general printing, paper, quality, and printing size settings. 24 1 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 14 .15. Prin t er O p t io n s p ag e 14 .3.10.2.4 . Jo b O p t io n s Pag e On the Jo b O pti o ns page, you can detail the printer job options. Click the Jo b O pti o ns label on the left to display the page. Edit the default settings to apply custom job options, such as number of copies, orientation, pages per side, scaling (increase or decrease the size of the printable area, which can be used to fit an oversize print area onto a smaller physical sheet of print medium), detailed text options, and custom job options. 24 2 Chapt er 1 4 . File and Print Servers Fig u re 14 .16 . Jo b O p t io n s p ag e 14 .3.10.2.5. In k/T o n er Levels Pag e The Ink/T o ner Level s page contains details on toner status if available and printer status messages. Click the Ink/T o ner Level s label on the left to display the page. 24 3 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 14 .17. In k/T o n er Levels p ag e 1 4 .3.1 0 .3. Managing Print Jo bs When you send a print job to the printer daemon, such as printing a text file from Emacs or printing an image from G IMP, the print job is added to the print spool queue. The print spool queue is a list of print jobs that have been sent to the printer and information about each print request, such as the status of the request, the job number, and more. D uring the printing process, the P ri nter Status icon appears in the N o t if icat io n Area on the panel. To check the status of a print job, click the P ri nter Status, which displays a window similar to Figure 14.18, “ GNOME Print Status” . Fig u re 14 .18. G N O ME Prin t St at u s To cancel, hold, release, reprint or authenticate a print job, select the job in the G N O ME Prin t St at u s and on the Jo b menu, click the respective command. 24 4 Chapt er 1 4 . File and Print Servers To view the list of print jobs in the print spool from a shell prompt, type the command l pstat -o . The last few lines look similar to the following: Examp le 14 .2. Examp le o f l pstat -o o u t p u t $ l pstat -o Charlie-60 16:42:11 GMT Aaron-61 16:42:44 GMT Ben-62 16:45:42 GMT twaugh 1024 Tue 08 Feb 2011 twaugh 1024 Tue 08 Feb 2011 root 1024 Tue 08 Feb 2011 If you want to cancel a print job, find the job number of the request with the command l pstat -o and then use the command cancel job number. For example, cancel 6 0 would cancel the print job in Example 14.2, “ Example of l pstat -o output” . You cannot cancel print jobs that were started by other users with the cancel command. However, you can enforce deletion of such job by issuing the cancel -U ro o t job_number command. To prevent such canceling, change the printer operation policy to Authenti cated to force ro o t authentication. You can also print a file directly from a shell prompt. For example, the command l p sampl e. txt prints the text file sampl e. txt. The print filter determines what type of file it is and converts it into a format the printer can understand. 14 .3.11. Addit ional Resources To learn more about printing on Red Hat Enterprise Linux, see the following resources. Inst alled Document at ion l p(1) — The manual page for the l p command that allows you to print files from the command line. l pr(1) — The manual page for the l pr command that allows you to print files from the command line. cancel (1) — The manual page for the command-line utility to remove print jobs from the print queue. mpag e(1) — The manual page for the command-line utility to print multiple pages on one sheet of paper. cupsd (8) — The manual page for the CUPS printer daemon. cupsd . co nf(5) — The manual page for the CUPS printer daemon configuration file. cl asses. co nf(5) — The manual page for the class configuration file for CUPS. l pstat(1) — The manual page for the l pstat command, which displays status information about classes, jobs, and printers. Online Document at ion 24 5 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide http://www.linuxprinting.org/ — The OpenPrinting group on the Linux Foundation website contains a large amount of information about printing in Linux. http://www.cups.org/ — The CUPS website provides documentation, FAQs, and newsgroups about CUPS. 24 6 Chapt er 1 5. Configuring NT P Using t he chrony Suit e Chapter 15. Configuring NTP Using the chrony Suite Accurate time keeping is important for a number of reasons in IT. In networking for example, accurate time stamps in packets and logs are required. In Linux systems, the NT P protocol is implemented by a daemon running in user space. The user space daemon updates the system clock running in the kernel. The system clock can keep time by using various clock sources. Usually, the Time Stamp Counter (TSC) is used. The TSC is a CPU register which counts the number of cycles since it was last reset. It is very fast, has a high resolution, and there are no interrupts. There is a choice between the daemons ntpd and chro nyd , which are available from the repositories in the ntp and chrony packages respectively. This section describes the use of the ch ro n y suite of utilities to update the system clock on systems that do not fit into the conventional permanently networked, always on, dedicated server category. 15.1. Int roduct ion t o t he chrony Suit e C h ro n y consists of chro nyd , a daemon that runs in user space, and ch ro n yc, a command line program for making adjustments to chro nyd . Systems which are not permanently connected, or not permanently powered up, take a relatively long time to adjust their system clocks with ntpd . This is because many small corrections are made based on observations of the clocks drift and offset. Temperature changes, which may be significant when powering up a system, affect the stability of hardware clocks. Although adjustments begin within a few milliseconds of booting a system, acceptable accuracy may take anything from ten seconds from a warm restart to a number of hours depending on your requirements, operating environment and hardware. ch ro n y is a different implementation of the NT P protocol than ntpd , it can adjust the system clock more rapidly. 15.1.1. Differences Bet ween nt pd and chronyd One of the main differences between ntpd and chro nyd is in the algorithms used to control the computer's clock. Things chro nyd can do better than ntpd are: chro nyd can work well when external time references are only intermittently accessible, whereas ntpd needs regular polling of time reference to work well. chro nyd can perform well even when the network is congested for longer periods of time. chro nyd can usually synchronize the clock faster and with better time accuracy. chro nyd quickly adapts to sudden changes in the rate of the clock, for example, due to changes in the temperature of the crystal oscillator, whereas ntpd may need a long time to settle down again. In the default configuration, chro nyd never steps the time after the clock has been synchronized at system start, in order not to upset other running programs. ntpd can be configured to never step the time too, but it has to use a different means of adjusting the clock, which has some disadvantages. chro nyd can adjust the rate of the clock on a Linux system in a larger range, which allows it to operate even on machines with a broken or unstable clock. For example, on some virtual machines. Things chro nyd can do that ntpd cannot do: 24 7 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide chro nyd provides support for isolated networks where the only method of time correction is manual entry. For example, by the administrator looking at a clock. chro nyd can examine the errors corrected at different updates to estimate the rate at which the computer gains or loses time, and use this estimate to trim the computer clock subsequently. chro nyd provides support to work out the rate of gain or loss of the real-time clock, the hardware clock, that maintains the time when the computer is turned off. It can use this data when the system boots to set the system time using an adjusted value of the time taken from the real-time clock. This is, at time of writing, only available in Linux. Things ntpd can do that chro nyd cannot do: ntpd fully supports NT P version 4 (RFC 5905), including broadcast, multicast, manycast clients and servers, and the orphan mode. It also supports extra authentication schemes based on public-key cryptography (RFC 5906). chro nyd uses NT P version 3 (RFC 1305), which is compatible with version 4. ntpd includes drivers for many reference clocks whereas chro nyd relies on other programs, for example g p sd , to access the data from the reference clocks. 15.1.2. Choosing Bet ween NT P Daemons C h ro n y should be considered for all systems which are frequently suspended or otherwise intermittently disconnected and reconnected to a network. Mobile and virtual systems for example. The NT P daemon (ntpd ) should be considered for systems which are normally kept permanently on. Systems which are required to use broadcast or multicast IP , or to perform authentication of packets with the Auto key protocol, should consider using ntpd . C h ro n y only supports symmetric key authentication using a message authentication code (MAC) with MD 5, SHA1 or stronger hash functions, whereas ntpd also supports the Auto key authentication protocol which can make use of the PKI system. Auto key is described in RFC 5906. 15.2. Underst anding chrony and It s Configurat ion 15.2.1. Underst anding chronyd The ch ro n y daemon, chro nyd , running in user space, makes adjustments to the system clock which is running in the kernel. It does this by consulting external time sources, using the NT P protocol, when ever network access allows it to do so. When external references are not available, chro nyd will use the last calculated drift stored in the drift file. It can also be commanded manually to make corrections, by ch ro n yc. 15.2.2. Underst anding chronyc The ch ro n y daemon, chro nyd , can be controlled by the command line utility ch ro n yc. This utility provides a command prompt which allows entering of a number of commands to make changes to chro nyd . The default configuration is for chro nyd to only accept commands from a local instance of ch ro n yc, but ch ro n yc can be used to alter the configuration so that chro nyd will allow external control. ch ro n yc can be run remotely after first configuring chro nyd to accept remote connections. The IP addresses allowed to connect to chro nyd should be tightly controlled. 15.2.3. Underst anding t he chrony Configurat ion Commands 24 8 Chapt er 1 5. Configuring NT P Using t he chrony Suit e The default configuration file for chro nyd is /etc/chro ny. co nf. The -f option can be used to specify an alternate configuration file path. See the chro nyd man page for further options. For a complete list of the directives that can be used see http://chrony.tuxfamily.org/manual.html#Configurationfile. Below is a selection of configuration options: C o mmen t s Comments should be preceded by #, % , ; or ! allo w Optionally specify a host, subnet, or network from which to allow NT P connections to a machine acting as NT P server. The default is not to allow connections. Examp les: 1. allow server1.example.com Use this form to specify a particular host, by its host name, to be allowed access. 2. allow 192.0.2.0/24 Use this form to specify a particular network to be allowed access. 3. allow 2001:db8::/32 Use this form to specify an IP v6 address to be allowed access. cmd allo w This is similar to the al l o w directive (see section al l o w), except that it allows control access (rather than NT P client access) to a particular subnet or host. (By “ control access” is meant that ch ro n yc can be run on those hosts and successfully connect to chro nyd on this computer.) The syntax is identical. There is also a cmd d eny al l directive with similar behavior to the cmd al l o w al l directive. d u mp d ir Path to the directory to save the measurement history across restarts of chro nyd (assuming no changes are made to the system clock behavior whilst it is not running). If this capability is to be used (via the d umpo nexi t command in the configuration file, or the d ump command in ch ro n yc), the d umpd i r command should be used to define the directory where the measurement histories are saved. d u mp o n exit If this command is present, it indicates that chro nyd should save the measurement history for each of its time sources recorded whenever the program exits. (See the d umpd i r command above). lo cal The l o cal keyword is used to allow chro nyd to appear synchronized to real time from the viewpoint of clients polling it, even if it has no current synchronization source. This option is normally used on the “ master” computer in an isolated network, where several computers are required to synchronize to one another, and the “ master” is kept in line with real time by manual input. 24 9 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide An example of the command is: local stratum 10 A large value of 10 indicates that the clock is so many hops away from a reference clock that its time is unreliable. If the computer ever has access to another computer which is ultimately synchronized to a reference clock, it will almost certainly be at a stratum less than 10. Therefore, the choice of a high value like 10 for the l o cal command prevents the machine’s own time from ever being confused with real time, were it ever to leak out to clients that have visibility of real servers. lo g The l o g command indicates that certain information is to be logged. It accepts the following options: measu remen t s This option logs the raw NT P measurements and related information to a file called measurements. l o g . st at ist ics This option logs information about the regression processing to a file called stati sti cs. l o g . t rackin g This option logs changes to the estimate of the system’s gain or loss rate, and any slews made, to a file called tracki ng . l o g . rt c This option logs information about the system’s real-time clock. ref clo cks This option logs the raw and filtered reference clock measurements to a file called refcl o cks. l o g . t emp co mp This option logs the temperature measurements and system rate compensations to a file called tempco mp. l o g . The log files are written to the directory specified by the l o g d i r command. An example of the command is: log measurements statistics tracking lo g d ir This directive allows the directory where log files are written to be specified. An example of the use of this directive is: logdir /var/log/chrony makest ep 250 Chapt er 1 5. Configuring NT P Using t he chrony Suit e Normally chro nyd will cause the system to gradually correct any time offset, by slowing down or speeding up the clock as required. In certain situations, the system clock may be so far adrift that this slewing process would take a very long time to correct the system clock. This directive forces chro nyd to step system clock if the adjustment is larger than a threshold value, but only if there were no more clock updates since chro nyd was started than a specified limit (a negative value can be used to disable the limit). This is particularly useful when using reference clocks, because the i ni tstepsl ew directive only works with NT P sources. An example of the use of this directive is: makestep 1000 10 This would step the system clock if the adjustment is larger than 1000 seconds, but only in the first ten clock updates. maxch an g e This directive sets the maximum allowed offset corrected on a clock update. The check is performed only after the specified number of updates to allow a large initial adjustment of the system clock. When an offset larger than the specified maximum occurs, it will be ignored for the specified number of times and then chro nyd will give up and exit (a negative value can be used to never exit). In both cases a message is sent to syslog. An example of the use of this directive is: maxchange 1000 1 2 After the first clock update, chro nyd will check the offset on every clock update, it will ignore two adjustments larger than 1000 seconds and exit on another one. maxu p d at eskew One of chro nyd 's tasks is to work out how fast or slow the computer’s clock runs relative to its reference sources. In addition, it computes an estimate of the error bounds around the estimated value. If the range of error is too large, it indicates that the measurements have not settled down yet, and that the estimated gain or loss rate is not very reliable. The maxupd ateskew parameter is the threshold for determining whether an estimate is too unreliable to be used. By default, the threshold is 1000 ppm. The format of the syntax is: maxupdateskew skew-in-ppm Typical values for skew-in-ppm might be 100 for a dial-up connection to servers over a telephone line, and 5 or 10 for a computer on a LAN. It should be noted that this is not the only means of protection against using unreliable estimates. At all times, chro nyd keeps track of both the estimated gain or loss rate, and the error bound on the estimate. When a new estimate is generated following another measurement from one of the sources, a weighted combination algorithm is used to update the master estimate. So if chro nyd has an existing highly-reliable master estimate and a new estimate is generated which has large error bounds, the existing master estimate will dominate in the new master estimate. n o clien t lo g This directive, which takes no arguments, specifies that client accesses are not to be logged. Normally they are logged, allowing statistics to be reported using the clients command in ch ro n yc. 251 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide reselect d ist When chro nyd selects synchronization source from available sources, it will prefer the one with minimum synchronization distance. However, to avoid frequent reselecting when there are sources with similar distance, a fixed distance is added to the distance for sources that are currently not selected. This can be set with the resel ectd i st option. By default, the distance is 100 microseconds. The format of the syntax is: reselectdist dist-in-seconds st rat u mweig h t The stratumwei g ht directive sets how much distance should be added per stratum to the synchronization distance when chro nyd selects the synchronization source from available sources. The format of the syntax is: stratumweight dist-in-seconds By default, dist-in-seconds is 1 second. This means that sources with lower stratum are usually preferred to sources with higher stratum even when their distance is significantly worse. Setting stratumwei g ht to 0 makes chro nyd ignore stratum when selecting the source. rt cf ile The rtcfi l e directive defines the name of the file in which chro nyd can save parameters associated with tracking the accuracy of the system’s real-time clock (RTC). The format of the syntax is: rtcfile /var/lib/chrony/rtc chro nyd saves information in this file when it exits and when the wri tertc command is issued in ch ro n yc. The information saved is the RTC’s error at some epoch, that epoch (in seconds since January 1 1970), and the rate at which the RTC gains or loses time. Not all real-time clocks are supported as their code is system-specific. Note that if this directive is used then the real-time clock should not be manually adjusted as this would interfere with ch ro n y's need to measure the rate at which the real-time clock drifts if it was adjusted at random intervals. rt csyn c The rtcsync directive is present in the /etc/chro ny. co nf file by default. This will inform the kernel the system clock is kept synchronized and the kernel will update the real-time clock every 11 minutes. 15.2.4 . Securit y wit h chronyc As access to ch ro n yc allows changing chro nyd just as editing the configuration files would, access to ch ro n yc should be limited. Passwords can be specified in the key file, written in ASCII or HEX, to restrict the use of ch ro n yc. One of the entries is used to restrict the use of operational commands and is referred to as the command key. In the default configuration, a random command key is generated automatically on start. It should not be necessary to specify or alter it manually. 252 Chapt er 1 5. Configuring NT P Using t he chrony Suit e Other entries in the key file can be used as NT P keys to authenticate packets received from remote NT P servers or peers. The two sides need to share a key with identical ID , hash type and password in their key file. This requires manually creating the keys and copying them over a secure medium, such as SSH. If the key ID was, for example, 10 then the systems that act as clients must have a line in their configuration files in the following format: server w.x.y.z key 10 peer w.x.y.z key 10 The location of the key file is specified in the /etc/chro ny. co nf file. The default entry in the configuration file is: keyfi l e /etc/chro ny. keys The command key number is specified in /etc/chro ny. co nf using the co mmand key directive, it is the key chro nyd will use for authentication of user commands. The directive in the configuration file takes the following form: commandkey 1 An example of the format of the default entry in the key file, /etc/chro ny. keys, for the command key is: 1 SHA1 HEX:A6CFC50C9C93AB6E5A19754C246242FC5471BCDF Where 1 is the key ID , SHA1 is the hash function to use, HEX is the format of the key, and A6 C FC 50 C 9 C 9 3AB6 E5A19 754 C 24 6 24 2FC 54 71BC D F is the key randomly generated when ch ro n yd was started for the first time. The key can be given in hexidecimal or ASCII format (the default). A manual entry in the key file, used to authenticate packets from certain NT P servers or peers, can be as simple as the following: 20 foobar Where 20 is the key ID and fo o bar is the secret authentication key. The default hash is MD 5, and ASCII is the default format for the key. By default, chro nyd is configured to listen for commands only from l o cal ho st (127. 0 . 0 . 1 and : : 1) on port 323. To access chro nyd remotely with ch ro n yc, any bi nd cmd ad d ress directives in the /etc/chro ny. co nf file should be removed to enable listening on all interfaces and the cmd al l o w directive should be used to allow commands from the remote IP address, network, or subnet. In addition, port 323 has to be opened in the firewall in order to connect from a remote system. Note that the al l o w directive is for NT P access whereas the cmd al l o w directive is to enable the receiving of remote commands. It is possible to make these changes temporarily using ch ro n yc running locally. Edit the configuration file to make persistent changes. The communication between ch ro n yc and ch ro n yd is done over UD P , so it needs to be authorized before issuing operational commands. To authorize, use the authhash and passwo rd commands as follows: chronyc> authhash SHA1 chronyc> passwo rd HEX: A6 C FC 50 C 9 C 9 3AB6 E5A19 754 C 24 6 24 2FC 54 71BC D F 200 OK 253 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide If ch ro n yc is used to configure the local ch ro n yd , the -a option will run the authhash and passwo rd commands automatically. Only the following commands can be used without providing a password: acti vi ty , authhash , d ns , exi t , hel p , passwo rd , q ui t , rtcd ata , so urces , so urcestats , tracki ng , wai tsync . 15.3. Using chrony 15.3.1. Inst alling chrony The ch ro n y suite is installed by default on some versions of Red Hat Enterprise Linux 7. If required, to ensure that it is, run the following command as ro o t: ~]# yum i nstal l chro ny The default location for the ch ro n y daemon is /usr/sbi n/chro nyd . The command line utility will be installed to /usr/bi n/chro nyc. 15.3.2. Checking t he St at us of chronyd To check the status of chro nyd , issue the following command: ~]$ systemctl status chro nyd chronyd.service - NTP client/server Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled) Active: active (running) since Wed 2013-06-12 22:23:16 CEST; 11h ago 15.3.3. St art ing chronyd To start chro nyd , issue the following command as ro o t: ~]# systemctl start chro nyd To ensure chro nyd starts automatically at system start, issue the following command as ro o t: ~]# systemctl enabl e chro nyd 15.3.4 . St opping chronyd To stop chro nyd , issue the following command as ro o t: ~]# systemctl sto p chro nyd To prevent chro nyd from starting automatically at system start, issue the following command as ro o t: ~]# systemctl d i sabl e chro nyd 15.3.5. Checking if chrony is Synchroniz ed 254 Chapt er 1 5. Configuring NT P Using t he chrony Suit e To check if ch ro n y is synchronized, make use of the tracki ng , so urces, and so urcestats commands. 1 5 .3.5 .1 . Che cking chro ny T racking To check ch ro n y tracking, issue the following command: ~]$ chro nyc tracki ng Reference ID : 1.2.3.4 (a.b.c) Stratum : 3 Ref time (UTC) : Fri Feb 3 15:00:29 2012 System time : 0.000001501 seconds slow of NTP time Last offset : -0.000001632 seconds RMS offset : 0.000002360 seconds Frequency : 331.898 ppm fast Residual freq : 0.004 ppm Skew : 0.154 ppm Root delay : 0.373169 seconds Root dispersion : 0.024780 seconds Update interval : 64.2 seconds Leap status : Normal The fields are as follows: R ef eren ce ID This is the reference ID and name (or IP address) if available, of the server to which the computer is currently synchronized. If this is 127. 127. 1. 1 it means the computer is not synchronized to any external source and that you have the “ local” mode operating (via the local command in ch ro n yc, or the l o cal directive in the /etc/chro ny. co nf file (see section l o cal )). St rat u m The stratum indicates how many hops away from a computer with an attached reference clock we are. Such a computer is a stratum-1 computer, so the computer in the example is two hops away (that is to say, a.b.c is a stratum-2 and is synchronized from a stratum-1). R ef t ime This is the time (UTC) at which the last measurement from the reference source was processed. Syst em t ime In normal operation, chro nyd never steps the system clock, because any jump in the timescale can have adverse consequences for certain application programs. Instead, any error in the system clock is corrected by slightly speeding up or slowing down the system clock until the error has been removed, and then returning to the system clock’s normal speed. A consequence of this is that there will be a period when the system clock (as read by other programs using the g etti meo fd ay() system call, or by the date command in the shell) will be different from chro nyd 's estimate of the current true time (which it reports to NT P clients when it is operating in server mode). The value reported on this line is the difference due to this effect. Last o f f set This is the estimated local offset on the last clock update. 255 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide R MS o f f set This is a long-term average of the offset value. Freq u en cy The “ frequency” is the rate by which the system’s clock would be wrong if chro nyd was not correcting it. It is expressed in ppm (parts per million). For example, a value of 1ppm would mean that when the system’s clock thinks it has advanced 1 second, it has actually advanced by 1.000001 seconds relative to true time. R esid u al f req This shows the “ residual frequency” for the currently selected reference source. This reflects any difference between what the measurements from the reference source indicate the frequency should be and the frequency currently being used. The reason this is not always zero is that a smoothing procedure is applied to the frequency. Each time a measurement from the reference source is obtained and a new residual frequency computed, the estimated accuracy of this residual is compared with the estimated accuracy (see skew next) of the existing frequency value. A weighted average is computed for the new frequency, with weights depending on these accuracies. If the measurements from the reference source follow a consistent trend, the residual will be driven to zero over time. Skew This is the estimated error bound on the frequency. R o o t d elay This is the total of the network path delays to the stratum-1 computer from which the computer is ultimately synchronized. In certain extreme situations, this value can be negative. (This can arise in a symmetric peer arrangement where the computers’ frequencies are not tracking each other and the network delay is very short relative to the turn-around time at each computer.) R o o t d isp ersio n This is the total dispersion accumulated through all the computers back to the stratum-1 computer from which the computer is ultimately synchronized. D ispersion is due to system clock resolution, statistical measurement variations etc. Leap st at u s This is the leap status, which can be Normal, Insert second, D elete second or Not synchronized. 1 5 .3.5 .2 . Che cking chro ny So urce s The sources command displays information about the current time sources that chro nyd is accessing. The optional argument -v can be specified, meaning verbose. In this case, extra caption lines are shown as a reminder of the meanings of the columns. ~]$ chro nyc so urces 210 Number of sources = 3 MS Name/IP address Stratum Poll Reach LastRx Last sample ======================================================================== ======= #* GPS0 0 4 377 11 -479ns[ -621ns] +/134ns 256 Chapt er 1 5. Configuring NT P Using t he chrony Suit e ^? a.b.c 43ms ^+ d.e.f 86ms 2 6 377 23 -923us[ -924us] +/- 1 6 377 21 -2629us[-2619us] +/- The columns are as follows: M This indicates the mode of the source. ^ means a server, = means a peer and # indicates a locally connected reference clock. S This column indicates the state of the sources. “ *” indicates the source to which chro nyd is currently synchronized. “ +” indicates acceptable sources which are combined with the selected source. “ -” indicates acceptable sources which are excluded by the combining algorithm. “ ?” indicates sources to which connectivity has been lost or whose packets do not pass all tests. “ x” indicates a clock which chro nyd thinks is a falseticker (its time is inconsistent with a majority of other sources). “ ~” indicates a source whose time appears to have too much variability. The “ ?” condition is also shown at start-up, until at least 3 samples have been gathered from it. N ame/IP ad d ress This shows the name or the IP address of the source, or reference ID for reference clocks. St rat u m This shows the stratum of the source, as reported in its most recently received sample. Stratum 1 indicates a computer with a locally attached reference clock. A computer that is synchronized to a stratum 1 computer is at stratum 2. A computer that is synchronized to a stratum 2 computer is at stratum 3, and so on. Po ll This shows the rate at which the source is being polled, as a base-2 logarithm of the interval in seconds. Thus, a value of 6 would indicate that a measurement is being made every 64 seconds. chro nyd automatically varies the polling rate in response to prevailing conditions. R each This shows the source’s reach register printed as an octal number. The register has 8 bits and is updated on every received or missed packet from the source. A value of 377 indicates that a valid reply was received for all of the last eight transmissions. Last R x This column shows how long ago the last sample was received from the source. This is normally in seconds. The letters m, h, d or y indicate minutes, hours, days or years. A value of 10 years indicates there were no samples received from this source yet. Last samp le This column shows the offset between the local clock and the source at the last measurement. The number in the square brackets shows the actual measured offset. This may be suffixed by ns (indicating nanoseconds), us (indicating microseconds), ms (indicating milliseconds), or s (indicating seconds). The number to the left of the square 257 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide brackets shows the original measurement, adjusted to allow for any slews applied to the local clock since. The number following the + /- indicator shows the margin of error in the measurement. Positive offsets indicate that the local clock is ahead of the source. 1 5 .3.5 .3. Che cking chro ny So urce St at ist ics The so urcestats command displays information about the drift rate and offset estimation process for each of the sources currently being examined by chro nyd . The optional argument -v can be specified, meaning verbose. In this case, extra caption lines are shown as a reminder of the meanings of the columns. ~]$ chro nyc so urcestats 210 Number of sources = 1 Name/IP Address NP NR Span Frequency Freq Skew Offset Std Dev ======================================================================== ======= abc.def.ghi 11 5 46m -0.001 0.045 1us 25us The columns are as follows: N ame/IP ad d ress This is the name or IP address of the NT P server (or peer) or reference ID of the reference clock to which the rest of the line relates. NP This is the number of sample points currently being retained for the server. The drift rate and current offset are estimated by performing a linear regression through these points. NR This is the number of runs of residuals having the same sign following the last regression. If this number starts to become too small relative to the number of samples, it indicates that a straight line is no longer a good fit to the data. If the number of runs is too low, chro nyd discards older samples and re-runs the regression until the number of runs becomes acceptable. Sp an This is the interval between the oldest and newest samples. If no unit is shown the value is in seconds. In the example, the interval is 46 minutes. Freq u en cy This is the estimated residual frequency for the server, in parts per million. In this case, the computer’s clock is estimated to be running 1 part in 10 9 slow relative to the server. Freq Skew This is the estimated error bounds on Freq (again in parts per million). O f f set This is the estimated offset of the source. St d D ev 258 Chapt er 1 5. Configuring NT P Using t he chrony Suit e This is the estimated sample standard deviation. 15.3.6. Manually Adjust ing t he Syst em Clock To update, or step, the system clock immediately, bypassing any adjustments in progress by slewing the clock, issue the following commands as ro o t: ~]# chro nyc chrony> passwo rd commandkey-password 200 OK chrony> makestep 200 OK Where commandkey-password is the command key or password stored in the key file. If the rtcfi l e directive is used, the real-time clock should not be manually adjusted. Random adjustments would interfere with ch ro n y's need to measure the rate at which the real-time clock drifts. If ch ro n yc is used to configure the local ch ro n yd , the -a will run the authhash and passwo rd commands automatically. This means that the interactive session illustrated above can be replaced by: chronyc -a makestep 15.4 . Set t ing Up chrony for Different Environment s 15.4 .1. Set t ing Up chrony for a Syst em Which is Infrequent ly Connect ed This example is intended for systems which use dial-on-demand connections. The normal configuration should be sufficient for mobile and virtual devices which connect intermittently. First, review and confirm that the default settings in the /etc/chro ny. co nf are similar to the following: driftfile /var/lib/chrony/drift commandkey 1 keyfile /etc/chrony.keys The command key ID is generated at install time and should correspond with the co mmand key value in the key file, /etc/chro ny. keys. Using your editor running as ro o t, add the addresses of four NT P servers as follows: server server server server 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org offline offline offline offline The o ffl i ne option can be useful in preventing systems from trying to activate connections. The ch ro n y daemon will wait for ch ro n yc to inform it that the system is connected to the network or Internet. 15.4 .2. Set t ing Up chrony for a Syst em in an Isolat ed Net work For a network that is never connected to the Internet, one computer is selected to be the master 259 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide timeserver. The other computers are either direct clients of the master, or clients of clients. On the master, the drift file must be manually set with the average rate of drift of the system clock. If the master is rebooted it will obtain the time from surrounding systems and take an average to set its system clock. Thereafter it resumes applying adjustments based on the drift file. The drift file will be updated automatically when the setti me command is used. On the system selected to be the master, using a text editor running as ro o t, edit the /etc/chro ny. co nf as follows: driftfile /var/lib/chrony/drift commandkey 1 keyfile /etc/chrony.keys initstepslew 10 client1 client3 client6 local stratum 8 manual allow 192.0.2.0 Where 19 2. 0 . 2. 0 is the network or subnet address from which the clients are allowed to connect. On the systems selected to be direct clients of the master, using a text editor running as ro o t, edit the /etc/chro ny. co nf as follows: server master driftfile /var/lib/chrony/drift logdir /var/log/chrony log measurements statistics tracking keyfile /etc/chrony.keys commandkey 24 local stratum 10 initstepslew 20 master allow 192.0.2.123 Where 19 2. 0 . 2. 123 is the address of the master, and master is the host name of the master. Clients with this configuration will resynchronize the master if it restarts. On the client systems which are not to be direct clients of the master, the /etc/chro ny. co nf file should be the same except that the l o cal and al l o w directives should be omitted. 15.5. Using chronyc 15.5.1. Using chronyc t o Cont rol chronyd To make changes to the local instance of chro nyd using the command line utility ch ro n yc in interactive mode, enter the following command as ro o t: ~]# chro nyc -a ch ro n yc must run as ro o t if some of the restricted commands are to be used. The -a option is for automatic authentication using the local keys when configuring chro nyd on the local system. See Section 15.2.4, “ Security with chronyc” for more information. The ch ro n yc command prompt will be displayed as follows: chronyc> 260 Chapt er 1 5. Configuring NT P Using t he chrony Suit e You can type hel p to list all of the commands. The utility can also be invoked in non-interactive command mode if called together with a command as follows: chro nyc command Note Changes made using ch ro n yc are not permanent, they will be lost after a chro nyd restart. For permanent changes, modify /etc/chro ny. co nf. 15.5.2. Using chronyc for Remot e Administ rat ion To configure ch ro n y to connect to a remote instance of chro nyd , issue a command in the following format: ~]$ chro nyc -h hostname Where hostname is the host name to connect to. The default is to connect to the local daemon. To configure ch ro n y to connect to a remote instance of chro nyd on a non-default port, issue a command in the following format: ~]$ chro nyc -h hostname -p port Where port is the port in use for controlling and monitoring by the remote instance of chro nyd . Note that commands issued at the ch ro n yc command prompt are not persistent. Only commands in the configuration file are persistent. The first command must be the passwo rd command at the ch ro n yc command prompt as follows: chronyc> passwo rd password 200 OK The password should not have any spaces. If the password is not an MD 5 hash, the hashed password must be preceded by the authhash command as follows: chronyc> authhash SHA1 chronyc> passwo rd HEX: A6 C FC 50 C 9 C 9 3AB6 E5A19 754 C 24 6 24 2FC 54 71BC D F 200 OK The password or hash associated with the command key for a remote system is best obtained by SSH. An SSH connection should be established to the remote machine and the ID of the command key from /etc/chro ny. co nf and the command key in /etc/chro ny. keys memorized or stored securely for the duration of the session. 15.6. Addit ional Resources 261 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The following sources of information provide additional resources regarding ch ro n y. 15.6.1. Inst alled Document at ion chro ny(1) man page — Introduces the ch ro n y daemon and the command-line interface tool. chro nyc(1) man page — D escribes the ch ro n yc command-line interface tool including commands and command options. chro nyd (1) man page — D escribes the ch ro n yd daemon including commands and command options. chro ny. co nf(5) man page — D escribes the ch ro n y configuration file. /usr/share/d o c/chro ny*/chro ny. txt — User guide for the ch ro n y suite. 15.6.2. Online Document at ion h t t p ://ch ro n y.t u xf amily.o rg /man u al.h t ml The online user guide for ch ro n y. 262 Chapt er 1 6 . Configuring NT P Using nt pd Chapter 16. Configuring NTP Using ntpd 16.1. Int roduct ion t o NT P The Network Time Protocol (NTP) enables the accurate dissemination of time and date information in order to keep the time clocks on networked computer systems synchronized to a common reference over the network or the Internet. Many standards bodies around the world have atomic clocks which may be made available as a reference. The satellites that make up the Global Position System contain more than one atomic clock, making their time signals potentially very accurate. Their signals can be deliberately degraded for military reasons. An ideal situation would be where each site has a server, with its own reference clock attached, to act as a site-wide time server. Many devices which obtain the time and date via low frequency radio transmissions or the Global Position System (GPS) exist. However for most situations, a range of publicly accessible time servers connected to the Internet at geographically dispersed locations can be used. These NT P servers provide “ Coordinated Universal Time” (UTC). Information about these time servers can found at www.pool.ntp.org. Accurate time keeping is important for a number of reasons in IT. In networking for example, accurate time stamps in packets and logs are required. Logs are used to investigate service and security issues and so time stamps made on different systems must be made by synchronized clocks to be of real value. As systems and networks become increasingly faster, there is a corresponding need for clocks with greater accuracy and resolution. In some countries there are legal obligations to keep accurately synchronized clocks. Please see www.ntp.org for more information. In Linux systems, NT P is implemented by a daemon running in user space. The default NT P user space daemon in Red Hat Enterprise Linux 7 is chro nyd . It must be disabled if you want to use the ntpd daemon. See Chapter 15, Configuring NTP Using the chrony Suite for information on ch ro n y. The user space daemon updates the system clock, which is a software clock running in the kernel. Linux uses a software clock as its system clock for better resolution than the typical embedded hardware clock referred to as the “ Real Time Clock” (RTC). See the rtc(4 ) and hwcl o ck(8) man pages for information on hardware clocks. The system clock can keep time by using various clock sources. Usually, the Time Stamp Counter (TSC) is used. The TSC is a CPU register which counts the number of cycles since it was last reset. It is very fast, has a high resolution, and there are no interrupts. On system start, the system clock reads the time and date from the RTC. The time kept by the RTC will drift away from actual time by up to 5 minutes per month due to temperature variations. Hence the need for the system clock to be constantly synchronized with external time references. When the system clock is being synchronized by ntpd , the kernel will in turn update the RTC every 11 minutes automatically. 16.2. NT P St rat a NT P servers are classified according to their synchronization distance from the atomic clocks which are the source of the time signals. The servers are thought of as being arranged in layers, or strata, from 1 at the top down to 15. Hence the word stratum is used when referring to a specific layer. Atomic clocks are referred to as Stratum 0 as this is the source, but no Stratum 0 packet is sent on the Internet, all stratum 0 atomic clocks are attached to a server which is referred to as stratum 1. These servers send out packets marked as Stratum 1. A server which is synchronized by means of packets marked stratum n belongs to the next, lower, stratum and will mark its packets as stratum n+ 1. Servers of the same stratum can exchange packets with each other but are still designated as belonging to just the one stratum, the stratum one below the best reference they are synchronized to. The designation Stratum 16 is used to indicate that the server is not currently synchronized to a reliable time source. Note that by default NT P clients act as servers for those systems in the stratum below them. Here is a summary of the NT P Strata: 263 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide St rat u m 0: Atomic Clocks and their signals broadcast over Radio and GPS GPS (Global Positioning System) Mobile Phone Systems Low Frequency Radio Broadcasts WWVB (Colorado, USA.), JJY-40 and JJY-60 (Japan), D CF77 (Germany), and MSF (United Kingdom) These signals can be received by dedicated devices and are usually connected by RS-232 to a system used as an organizational or site-wide time server. St rat u m 1: Computer with radio clock, GPS clock, or atomic clock attached St rat u m 2: Reads from stratum 1; Serves to lower strata St rat u m 3: Reads from stratum 2; Serves to lower strata St rat u m n+1: Reads from stratum n; Serves to lower strata St rat u m 15: Reads from stratum 14; This is the lowest stratum. This process continues down to Stratum 15 which is the lowest valid stratum. The label Stratum 16 is used to indicated an unsynchronized state. 16.3. Underst anding NT P The version of NT P used by Red Hat Enterprise Linux is as described in RFC 1305 Network Time Protocol (Version 3) Specification, Implementation and Analysis and RFC 5905 Network Time Protocol Version 4: Protocol and Algorithms Specification This implementation of NT P enables sub-second accuracy to be achieved. Over the Internet, accuracy to 10s of milliseconds is normal. On a Local Area Network (LAN), 1 ms accuracy is possible under ideal conditions. This is because clock drift is now accounted and corrected for, which was not done in earlier, simpler, time protocol systems. A resolution of 233 picoseconds is provided by using 64-bit time stamps. The first 32-bits of the time stamp is used for seconds, the last 32-bits are used for fractions of seconds. NT P represents the time as a count of the number of seconds since 00:00 (midnight) 1 January, 1900 GMT. As 32-bits is used to count the seconds, this means the time will “ roll over” in 2036. However NT P works on the difference between time stamps so this does not present the same level of problem as other implementations of time protocols have done. If a hardware clock that is within 68 years of the correct time is available at boot time then NT P will correctly interpret the current date. The NT P 4 specification provides for an “ Era Number” and an “ Era Offset” which can be used to make software more robust when dealing with time lengths of more than 68 years. Note, please do not confuse this with the Unix Year 2038 problem. 264 Chapt er 1 6 . Configuring NT P Using nt pd The NT P protocol provides additional information to improve accuracy. Four time stamps are used to allow the calculation of round-trip time and server response time. In order for a system in its role as NT P client to synchronize with a reference time server, a packet is sent with an “ originate time stamp” . When the packet arrives, the time server adds a “ receive time stamp” . After processing the request for time and date information and just before returning the packet, it adds a “ transmit time stamp” . When the returning packet arrives at the NT P client, a “ receive time stamp” is generated. The client can now calculate the total round trip time and by subtracting the processing time derive the actual traveling time. By assuming the outgoing and return trips take equal time, the single-trip delay in receiving the NT P data is calculated. The full NT P algorithm is much more complex than presented here. When a packet containing time information is received it is not immediately responded to, but is first subject to validation checks and then processed together with several other time samples to arrive at an estimate of the time. This is then compared to the system clock to determine the time offset, the difference between the system clock's time and what ntpd has determined the time should be. The system clock is adjusted slowly, at most at a rate of 0.5ms per second, to reduce this offset by changing the frequency of the counter being used. It will take at least 2000 seconds to adjust the clock by 1 second using this method. This slow change is referred to as slewing and cannot go backwards. If the time offset of the clock is more than 128ms (the default setting), ntpd can “ step” the clock forwards or backwards. If the time offset at system start is greater than 1000 seconds then the user, or an installation script, should make a manual adjustment. See Chapter 2, Configuring the Date and Time. With the -g option to the ntpd command (used by default), any offset at system start will be corrected, but during normal operation only offsets of up to 1000 seconds will be corrected. Some software may fail or produce an error if the time is changed backwards. For systems that are sensitive to step changes in the time, the threshold can be changed to 600s instead of 128ms using the -x option (unrelated to the -g option). Using the -x option to increase the stepping limit from 0.128s to 600s has a drawback because a different method of controlling the clock has to be used. It disables the kernel clock discipline and may have a negative impact on the clock accuracy. The -x option can be added to the /etc/sysco nfi g /ntpd configuration file. 16.4 . Underst anding t he Drift File The drift file is used to store the frequency offset between the system clock running at its nominal frequency and the frequency required to remain in synchronization with UTC. If present, the value contained in the drift file is read at system start and used to correct the clock source. Use of the drift file reduces the time required to achieve a stable and accurate time. The value is calculated, and the drift file replaced, once per hour by ntpd . The drift file is replaced, rather than just updated, and for this reason the drift file must be in a directory for which the ntpd has write permissions. 16.5. UT C, T imez ones, and DST As NT P is entirely in UTC (Universal Time, Coordinated), Timezones and D ST (D aylight Saving Time) are applied locally by the system. The file /etc/l o cal ti me is a copy of, or symlink to, a zone information file from /usr/share/zo nei nfo . The RTC may be in localtime or in UTC, as specified by the 3rd line of /etc/ad jti me, which will be one of LOCAL or UTC to indicate how the RTC clock has been set. Users can easily change this setting using the checkbox System C l o ck Uses UT C in the D at e an d T ime graphical configuration tool. See Chapter 2, Configuring the Date and Time for information on how to use that tool. Running the RTC in UTC is recommended to avoid various problems when daylight saving time is changed. The operation of ntpd is explained in more detail in the man page ntpd (8). The resources section lists useful sources of information. See Section 16.20, “ Additional Resources” . 16.6. Aut hent icat ion Opt ions for NT P 265 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide NT P v4 added support for the Autokey Security Architecture, which is based on public asymmetric cryptography while retaining support for symmetric key cryptography. The Autokey Security Architecture is described in RFC 5906 Network Time Protocol Version 4: Autokey Specification. The man page ntp_auth(5) describes the authentication options and commands for ntpd . An attacker on the network can attempt to disrupt a service by sending NT P packets with incorrect time information. On systems using the public pool of NT P servers, this risk is mitigated by having more than three NT P servers in the list of public NT P servers in /etc/ntp. co nf. If only one time source is compromised or spoofed, ntpd will ignore that source. You should conduct a risk assessment and consider the impact of incorrect time on your applications and organization. If you have internal time sources you should consider steps to protect the network over which the NT P packets are distributed. If you conduct a risk assessment and conclude that the risk is acceptable, and the impact to your applications minimal, then you can choose not to use authentication. The broadcast and multicast modes require authentication by default. If you have decided to trust the network then you can disable authentication by using d i sabl e auth directive in the ntp. co nf file. Alternatively, authentication needs to be configured by using SHA1 or MD 5 symmetric keys, or by public (asymmetric) key cryptography using the Autokey scheme. The Autokey scheme for asymmetric cryptography is explained in the ntp_auth(8) man page and the generation of keys is explained in ntp-keyg en(8). To implement symmetric key cryptography, see Section 16.17.12, “ Configuring Symmetric Authentication Using a Key” for an explanation of the key option. 16.7. Managing t he T ime on Virt ual Machines Virtual machines cannot access a real hardware clock and a virtual clock is not stable enough as the stability is dependent on the host systems work load. For this reason, para-virtualized clocks should be provided by the virtualization application in use. On Red Hat Enterprise Linux with K VM the default clock source is kvm-cl o ck. See the KVM guest timing management chapter of the Red Hat Enterprise Linux 7 Virtualization Deployment and Administration Guide. 16.8. Underst anding Leap Seconds Greenwich Mean Time (GMT) was derived by measuring the solar day, which is dependent on the Earth's rotation. When atomic clocks were first made, the potential for more accurate definitions of time became possible. In 1958, International Atomic Time (TAI) was introduced based on the more accurate and very stable atomic clocks. A more accurate astronomical time, Universal Time 1 (UT1), was also introduced to replace GMT. The atomic clocks are in fact far more stable than the rotation of the Earth and so the two times began to drift apart. For this reason UTC was introduced as a practical measure. It is kept within one second of UT1 but to avoid making many small trivial adjustments it was decided to introduce the concept of a leap second in order to reconcile the difference in a manageable way. The difference between UT1 and UTC is monitored until they drift apart by more than half a second. Then only is it deemed necessary to introduce a one second adjustment, forward or backward. D ue to the erratic nature of the Earth's rotational speed, the need for an adjustment cannot be predicted far into the future. The decision as to when to make an adjustment is made by the International Earth Rotation and Reference Systems Service (IERS). However, these announcements are important only to administrators of Stratum 1 servers because NT P transmits information about pending leap seconds and applies them automatically. 16.9. Underst anding t he nt pd Configurat ion File The daemon, ntpd , reads the configuration file at system start or when the service is restarted. The default location for the file is /etc/ntp. co nf and you can view the file by entering the following command: 266 Chapt er 1 6 . Configuring NT P Using nt pd ~]$ l ess /etc/ntp. co nf The configuration commands are explained briefly later in this chapter, see Section 16.17, “ Configure NTP” , and more verbosely in the ntp. co nf(5) man page. Here follows a brief explanation of the contents of the default configuration file: T h e d rif t f ile en t ry A path to the drift file is specified, the default entry on Red Hat Enterprise Linux is: driftfile /var/lib/ntp/drift If you change this be certain that the directory is writable by ntpd . The file contains one value used to adjust the system clock frequency after every system or service start. See Understanding the D rift File for more information. T h e access co n t ro l en t ries The following line sets the default access control restriction: restrict default nomodify notrap nopeer noquery The no mo d i fy options prevents any changes to the configuration. The no trap option prevents ntpd c control message protocol traps. The no peer option prevents a peer association being formed. The no q uery option prevents ntpq and ntpd c queries, but not time queries, from being answered. Important The ntpq and ntpd c queries can be used in amplification attacks, therefore do not remove the no q uery option from the restri ct d efaul t command on publicly accessible systems. See CVE-2013-5211 for more details. Addresses within the range 127. 0 . 0 . 0 /8 are sometimes required by various processes or applications. As the " restrict default" line above prevents access to everything not explicitly allowed, access to the standard loopback address for IP v4 and IP v6 is permitted by means of the following lines: # the administrative functions. restrict 127.0.0.1 restrict ::1 Addresses can be added underneath if specifically required by another application. Hosts on the local network are not permitted because of the " restrict default" line above. To change this, for example to allow hosts from the 19 2. 0 . 2. 0 /24 network to query the time and statistics but nothing more, a line in the following format is required: 267 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide restrict 192.0.2.0 mask 255.255.255.0 nomodify notrap nopeer To allow unrestricted access from a specific host, for example 19 2. 0 . 2. 250 /32, a line in the following format is required: restrict 192.0.2.250 A mask of 255. 255. 255. 255 is applied if none is specified. The restrict commands are explained in the ntp_acc(5) man page. T h e p u b lic servers en t ry By default, the ntp. co nf file contains four public server entries: server server server server 0.rhel.pool.ntp.org 1.rhel.pool.ntp.org 2.rhel.pool.ntp.org 3.rhel.pool.ntp.org iburst iburst iburst iburst T h e b ro ad cast mu lt icast servers en t ry By default, the ntp. co nf file contains some commented out examples. These are largely self explanatory. See Section 16.17, “ Configure NTP” for the explanation of the specific commands. If required, add your commands just below the examples. Note When the D HC P client program, d h clien t , receives a list of NT P servers from the D HC P server, it adds them to ntp. co nf and restarts the service. To disable that feature, add P EER NT P = no to /etc/sysco nfi g /netwo rk. 16.10. Underst anding t he nt pd Sysconfig File The file will be read by the ntpd init script on service start. The default contents is as follows: # Command line options for ntpd OPTIONS="-g" The -g option enables ntpd to ignore the offset limit of 1000s and attempt to synchronize the time even if the offset is larger than 1000s, but only on system start. Without that option n t p d will exit if the time offset is greater than 1000s. It will also exit after system start if the service is restarted and the offset is greater than 1000s even with the -g option. 16.11. Disabling chrony In order to use ntpd the default user space daemon, chro nyd , must be stopped and disabled. Issue the following command as ro o t: ~]# systemctl sto p chro nyd 268 Chapt er 1 6 . Configuring NT P Using nt pd To prevent it restarting at system start, issue the following command as ro o t: ~]# systemctl d i sabl e chro nyd To check the status of chro nyd , issue the following command: ~]$ systemctl status chro nyd 16.12. Checking if t he NT P Daemon is Inst alled To check if ntpd is installed, enter the following command as ro o t: ~]# yum i nstal l ntp NT P is implemented by means of the daemon or service ntpd , which is contained within the ntp package. 16.13. Inst alling t he NT P Daemon (nt pd) To install ntpd , enter the following command as ro o t: ~]# yum i nstal l ntp To enable ntpd at system start, enter the following command as ro o t: ~]# systemctl enabl e ntpd 16.14 . Checking t he St at us of NT P To check if ntpd is running and configured to run at system start, issue the following command: ~]$ systemctl status ntpd To obtain a brief status report from ntpd , issue the following command: ~]$ ntpstat unsynchronised time server re-starting polling server every 64 s ~]$ ntpstat synchronised to NTP server (10.5.26.10) at stratum 2 time correct to within 52 ms polling server every 1024 s 16.15. Configure t he Firewall t o Allow Incoming NT P Packet s 269 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The NT P traffic consists of UD P packets on port 123 and needs to be permitted through network and host-based firewalls in order for NT P to function. Check if the firewall is configured to allow incoming NT P traffic for clients using the graphical Firewall C o n f ig u rat io n tool. To start the graphical f irewall- co n f ig tool, press the Super key to enter the Activities Overview, type fi rewal l and then press Enter. The Fi rewal l C o nfi g urati o n window opens. You will be prompted for your user password. To start the graphical firewall configuration tool using the command line, enter the following command as ro o t user: ~]# fi rewal l -co nfi g The Fi rewal l C o nfi g urati o n window opens. Note, this command can be run as normal user but you will then be prompted for the ro o t password from time to time. Look for the word “ Connected” in the lower left corner. This indicates that the f irewall- co n f ig tool is connected to the user space daemon, fi rewal l d . 16.15.1. Change t he Firewall Set t ings To immediately change the current firewall settings, ensure the drop-down selection menu labeled C o nfi g urati o n is set to R u n t ime. Alternatively, to edit the settings to be applied at the next system start, or firewall reload, select Perman en t from the drop-down list. Note When making changes to the firewall settings in R u n t ime mode, your selection takes immediate effect when you set or clear the check box associated with the service. You should keep this in mind when working on a system that may be in use by other users. When making changes to the firewall settings in Perman en t mode, your selection will only take effect when you reload the firewall or the system restarts. To reload the firewall, select the O p t io n s menu and select R elo ad Firewall. 16.15.2. Open Port s in t he Firewall for NT P Packet s To permit traffic through the firewall to a certain port, start the f irewall- co n f ig tool and select the network zone whose settings you want to change. Select the P o rts tab and then click the Ad d button. The P o rt and P ro to co l window opens. Enter the port number 123 and select u d p from the drop-down list. 16.16. Configure nt pdat e Servers The purpose of the ntpd ate service is to set the clock during system boot. This was used previously to ensure that the services started after ntpd ate would have the correct time and not observe a jump in the clock. The use of ntpd ate and the list of step-tickers is considered deprecated and so Red Hat Enterprise Linux 7 uses the -g option to the ntpd command and not ntpd ate by default. 270 Chapt er 1 6 . Configuring NT P Using nt pd The ntpd ate service in Red Hat Enterprise Linux 7 is mostly useful only when used alone without ntpd . With syst emd , which starts services in parallel, enabling the ntpd ate service will not ensure that other services started after it will have correct time unless they specify an ordering dependency on ti me-sync. targ et, which is provided by the ntpd ate service. In order to ensure a service starts with correct time, add After= ti me-sync. targ et to the service and enable one of the services which provide the target (ntpd ate or sn t p ). Some services on Red Hat Enterprise Linux 7 have the dependency included by default ( for example, d hcpd , d hcpd 6 , and cro nd ). To check if the ntpd ate service is enabled to run at system start, issue the following command: ~]$ systemctl status ntpd ate To enable the service to run at system start, issue the following command as ro o t: ~]# systemctl enabl e ntpd ate In Red Hat Enterprise Linux 7 the default /etc/ntp/step-ti ckers file contains 0 . rhel . po o l . ntp. o rg . To configure additional ntpd ate servers, using a text editor running as ro o t, edit /etc/ntp/step-ti ckers. The number of servers listed is not very important as ntpd ate will only use this to obtain the date information once when the system is starting. If you have an internal time server then use that host name for the first line. An additional host on the second line as a backup is sensible. The selection of backup servers and whether the second host is internal or external depends on your risk assessment. For example, what is the chance of any problem affecting the first server also affecting the second server? Would connectivity to an external server be more likely to be available than connectivity to internal servers in the event of a network failure disrupting access to the first server? 16.17. Configure NT P To change the default configuration of the NT P service, use a text editor running as ro o t user to edit the /etc/ntp. co nf file. This file is installed together with ntpd and is configured to use time servers from the Red Hat pool by default. The man page ntp. co nf(5) describes the command options that can be used in the configuration file apart from the access and rate limiting commands which are explained in the ntp_acc(5) man page. 16.17.1. Configure Access Cont rol t o an NT P Service To restrict or control access to the NT P service running on a system, make use of the restri ct command in the ntp. co nf file. See the commented out example: # Hosts on local network are less restricted. #restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap The restri ct command takes the following form: restri ct option where option is one or more of: i g no re — All packets will be ignored, including ntpq and ntpd c queries. ko d — a “ Kiss-o'-death” packet is to be sent to reduce unwanted queries. 271 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide l i mi ted — do not respond to time service requests if the packet violates the rate limit default values or those specified by the d i scard command. ntpq and ntpd c queries are not affected. For more information on the d i scard command and the default values, see Section 16.17.2, “ Configure Rate Limiting Access to an NTP Service” . l o wpri o trap — traps set by matching hosts to be low priority. no mo d i fy — prevents any changes to the configuration. no q uery — prevents ntpq and ntpd c queries, but not time queries, from being answered. no peer — prevents a peer association being formed. no serve — deny all packets except ntpq and ntpd c queries. no trap — prevents ntpd c control message protocol traps. no trust — deny packets that are not cryptographically authenticated. ntppo rt — modify the match algorithm to only apply the restriction if the source port is the standard NT P UD P port 123. versi o n — deny packets that do not match the current NT P version. To configure rate limit access to not respond at all to a query, the respective restri ct command has to have the l i mi ted option. If ntpd should reply with a Ko D packet, the restri ct command needs to have both l i mi ted and ko d options. The ntpq and ntpd c queries can be used in amplification attacks (see CVE-2013-5211 for more details), do not remove the no q uery option from the restri ct d efaul t command on publicly accessible systems. 16.17.2. Configure Rat e Limit ing Access t o an NT P Service To enable rate limiting access to the NT P service running on a system, add the l i mi ted option to the restri ct command as explained in Section 16.17.1, “ Configure Access Control to an NTP Service” . If you do not want to use the default discard parameters, then also use the d i scard command as explained here. The d i scard command takes the following form: d i scard [averag e value] [mi ni mum value] [mo ni to r value] averag e — specifies the minimum average packet spacing to be permitted, it accepts an argument in log 2 seconds. The default value is 3 (2 3 equates to 8 seconds). mi ni mum — specifies the minimum packet spacing to be permitted, it accepts an argument in log 2 seconds. The default value is 1 (2 1 equates to 2 seconds). mo ni to r — specifies the discard probability for packets once the permitted rate limits have been exceeded. The default value is 3000 seconds. This option is intended for servers that receive 1000 or more requests per second. Examples of the d i scard command are as follows: discard average 4 272 Chapt er 1 6 . Configuring NT P Using nt pd discard average 4 minimum 2 16.17.3. Adding a Peer Address To add the address of a peer, that is to say, the address of a server running an NT P service of the same stratum, make use of the peer command in the ntp. co nf file. The peer command takes the following form: peer address where address is an IP unicast address or a D NS resolvable name. The address must only be that of a system known to be a member of the same stratum. Peers should have at least one time source that is different to each other. Peers are normally systems under the same administrative control. 16.17.4 . Adding a Server Address To add the address of a server, that is to say, the address of a server running an NT P service of a higher stratum, make use of the server command in the ntp. co nf file. The server command takes the following form: server address where address is an IP unicast address or a D NS resolvable name. The address of a remote reference server or local reference clock from which packets are to be received. 16.17.5. Adding a Broadcast or Mult icast Server Address To add a broadcast or multicast address for sending, that is to say, the address to broadcast or multicast NT P packets to, make use of the bro ad cast command in the ntp. co nf file. The broadcast and multicast modes require authentication by default. See Section 16.6, “ Authentication Options for NTP” . The bro ad cast command takes the following form: bro ad cast address where address is an IP broadcast or multicast address to which packets are sent. This command configures a system to act as an NT P broadcast server. The address used must be a broadcast or a multicast address. Broadcast address implies the IP v4 address 255. 255. 255. 255. By default, routers do not pass broadcast messages. The multicast address can be an IP v4 Class D address, or an IP v6 address. The IANA has assigned IP v4 multicast address 224 . 0 . 1. 1 and IP v6 address FF0 5: : 10 1 (site local) to NT P . Administratively scoped IP v4 multicast addresses can also be used, as described in RFC 2365 Administratively Scoped IP Multicast. 16.17.6. Adding a Manycast Client Address To add a manycast client address, that is to say, to configure a multicast address to be used for NT P server discovery, make use of the manycastcl i ent command in the ntp. co nf file. 273 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The manycastcl i ent command takes the following form: manycastcl i ent address where address is an IP multicast address from which packets are to be received. The client will send a request to the address and select the best servers from the responses and ignore other servers. NT P communication then uses unicast associations, as if the discovered NT P servers were listed in ntp. co nf. This command configures a system to act as an NT P client. Systems can be both client and server at the same time. 16.17.7. Adding a Broadcast Client Address To add a broadcast client address, that is to say, to configure a broadcast address to be monitored for broadcast NT P packets, make use of the bro ad castcl i ent command in the ntp. co nf file. The bro ad castcl i ent command takes the following form: bro ad castcl i ent Enables the receiving of broadcast messages. Requires authentication by default. See Section 16.6, “ Authentication Options for NTP” . This command configures a system to act as an NT P client. Systems can be both client and server at the same time. 16.17.8. Adding a Manycast Server Address To add a manycast server address, that is to say, to configure an address to allow the clients to discover the server by multicasting NT P packets, make use of the manycastserver command in the ntp. co nf file. The manycastserver command takes the following form: manycastserver address Enables the sending of multicast messages. Where address is the address to multicast to. This should be used together with authentication to prevent service disruption. This command configures a system to act as an NT P server. Systems can be both client and server at the same time. 16.17.9. Adding a Mult icast Client Address To add a multicast client address, that is to say, to configure a multicast address to be monitored for multicast NT P packets, make use of the mul ti castcl i ent command in the ntp. co nf file. The mul ti castcl i ent command takes the following form: mul ti castcl i ent address Enables the receiving of multicast messages. Where address is the address to subscribe to. This should be used together with authentication to prevent service disruption. 274 Chapt er 1 6 . Configuring NT P Using nt pd This command configures a system to act as an NT P client. Systems can be both client and server at the same time. 16.17.10. Configuring t he Burst Opt ion Using the burst option against a public server is considered abuse. D o not use this option with public NT P servers. Use it only for applications within your own organization. To increase the average quality of time offset statistics, add the following option to the end of a server command: burst At every poll interval, when the server responds, the system will send a burst of up to eight packets instead of the usual one packet. For use with the server command to improve the average quality of the time-offset calculations. 16.17.11. Configuring t he iburst Opt ion To improve the time taken for initial synchronization, add the following option to the end of a server command: i burst At every poll interval, send a burst of eight packets instead of one. When the server is not responding, packets are sent 16s apart. When the server responds, packets are sent every 2s. For use with the server command to reduce the time taken for initial synchronization. This is now a default option in the configuration file. 16.17.12. Configuring Symmet ric Aut hent icat ion Using a Key To configure symmetric authentication using a key, add the following option to the end of a server or peer command: key number where number is in the range 1 to 6 5534 inclusive. This option enables the use of a message authentication code (MAC) in packets. This option is for use with the peer, server, bro ad cast, and manycastcl i ent commands. The option can be used in the /etc/ntp. co nf file as follows: server 192.168.1.1 key 10 broadcast 192.168.1.255 key 20 manycastclient 239.255.254.254 key 30 See also Section 16.6, “ Authentication Options for NTP” . 16.17.13. Configuring t he Poll Int erval To change the default poll interval, add the following options to the end of a server or peer command: mi npo l l value and maxpo l l value 275 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Options to change the default poll interval, where the interval in seconds will be calculated by raising 2 to the power of value, in other words, the interval is expressed in log 2 seconds. The default mi npo l l value is 6, 2 6 equates to 64s. The default value for maxpo l l is 10, which equates to 1024s. Allowed values are in the range 3 to 17 inclusive, which equates to 8s to 36.4h respectively. These options are for use with the peer or server. Setting a shorter maxpo l l may improve clock accuracy. 16.17.14 . Configuring Server Preference To specify that a particular server should be preferred above others of similar statistical quality, add the following option to the end of a server or peer command: prefer Use this server for synchronization in preference to other servers of similar statistical quality. This option is for use with the peer or server commands. 16.17.15. Configuring t he T ime-t o-Live for NT P Packet s To specify that a particular time-to-live (TTL) value should be used in place of the default, add the following option to the end of a server or peer command: ttl value Specify the time-to-live value to be used in packets sent by broadcast servers and multicast NT P servers. Specify the maximum time-to-live value to use for the “ expanding ring search” by a manycast client. The default value is 127. 16.17.16. Configuring t he NT P Version t o Use To specify that a particular version of NT P should be used in place of the default, add the following option to the end of a server or peer command: versi o n value Specify the version of NT P set in created NT P packets. The value can be in the range 1 to 4 . The default is 4 . 16.18. Configuring t he Hardware Clock Updat e To configure the system clock to update the hardware clock, also known as the real-time clock (RTC), once after executing n t p d at e, add the following line to /etc/sysco nfi g /ntpd ate: SYNC_HWCLOCK=yes To update the hardware clock from the system clock, issue the following command as ro o t: ~]# hwcl o ck --systo hc When the system clock is being synchronized by ntpd or chro nyd , the kernel will in turn update the RTC every 11 minutes automatically. 276 Chapt er 1 6 . Configuring NT P Using nt pd 16.19. Configuring Clock Sources To list the available clock sources on your system, issue the following commands: ~]$ cd /sys/d evi ces/system/cl o ckso urce/cl o ckso urce0 / clocksource0]$ cat avai l abl e_cl o ckso urce kvm-clock tsc hpet acpi_pm clocksource0]$ cat current_cl o ckso urce kvm-clock In the above example, the kernel is using kvm- clo ck. This was selected at boot time as this is a virtual machine. To override the default clock source, append the cl o ckso urce directive to the GRUB_CMD LINE_LINUX line in the /etc/d efaul t/g rub file and rebuild the g rub. cfg file. For example: GRUB_CMDLINE_LINUX="rd.lvm.lv=rhel/root crashkernel=auto rd.lvm.lv=rhel/swap vconsole.font=latarcyrheb-sun16 vconsole.keymap=us rhgb quiet cl o ckso urce= tsc" The available clock source is architecture dependent. Rebuild the g rub. cfg file as follows: On BIOS-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/g rub2/g rub. cfg On UEFI-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/efi /EFI/red hat/g rub. cfg See Section 24.1, “ Configuring the GRUB 2 Boot Loader” for more information on the g rub. cfg file. 16.20. Addit ional Resources The following sources of information provide additional resources regarding NT P and ntpd . 16.20.1. Inst alled Document at ion ntpd (8) man page — D escribes ntpd in detail, including the command line options. ntp. co nf(5) man page — Contains information on how to configure associations with servers and peers. ntpq (8) man page — D escribes the NT P query utility for monitoring and querying an NT P server. ntpd c(8) man page — D escribes the ntpd utility for querying and changing the state of ntpd . ntp_auth(5) man page — D escribes authentication options, commands, and key management for ntpd . 277 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ntp_keyg en(8) man page — D escribes generating public and private keys for ntpd . ntp_acc(5) man page — D escribes access control options using the restri ct command. ntp_mo n(5) man page — D escribes monitoring options for the gathering of statistics. ntp_cl o ck(5) man page — D escribes commands for configuring reference clocks. ntp_mi sc(5) man page — D escribes miscellaneous options. ntp_d eco d e(5) man page — Lists the status words, event messages and error codes used for ntpd reporting and monitoring. ntpstat(8) man page — D escribes a utility for reporting the synchronization state of the NT P daemon running on the local machine. ntpti me(8) man page — D escribes a utility for reading and setting kernel time variables. ti ckad j(8) man page — D escribes a utility for reading, and optionally setting, the length of the tick. 16.20.2. Useful Websit es h t t p ://d o c.n t p .o rg / The NTP D ocumentation Archive h t t p ://www.eecis.u d el.ed u /~ mills/n t p .h t ml Network Time Synchronization Research Project. h t t p ://www.eecis.u d el.ed u /~ mills/n t p /h t ml/man yo p t .h t ml Information on Automatic Server D iscovery in NT P v4 . 278 Chapt er 1 7 . Configuring PT P Using pt p4 l Chapter 17. Configuring PTP Using ptp4l 17.1. Int roduct ion t o PT P The Precision Time Protocol (PTP) is a protocol used to synchronize clocks in a network. When used in conjunction with hardware support, P T P is capable of sub-microsecond accuracy, which is far better than is normally obtainable with NT P . P T P support is divided between the kernel and user space. The kernel in Red Hat Enterprise Linux includes support for P T P clocks, which are provided by network drivers. The actual implementation of the protocol is known as lin u xp t p , a P T P v2 implementation according to the IEEE standard 1588 for Linux. The linuxptp package includes the p t p 4 l and p h c2sys programs for clock synchronization. The p t p 4 l program implements the P T P boundary clock and ordinary clock. With hardware time stamping, it is used to synchronize the P T P hardware clock to the master clock, and with software time stamping it synchronizes the system clock to the master clock. The p h c2sys program is needed only with hardware time stamping, for synchronizing the system clock to the P T P hardware clock on the network interface card (NIC). 17.1.1. Underst anding PT P The clocks synchronized by P T P are organized in a master-slave hierarchy. The slaves are synchronized to their masters which may be slaves to their own masters. The hierarchy is created and updated automatically by the best master clock (BMC) algorithm, which runs on every clock. When a clock has only one port, it can be master or slave, such a clock is called an ordinary clock (OC). A clock with multiple ports can be master on one port and slave on another, such a clock is called a boundary clock (BC). The top-level master is called the grandmaster clock, which can be synchronized by using a Global Positioning System (GPS) time source. By using a GPS-based time source, disparate networks can be synchronized with a high-degree of accuracy. 279 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 17.1. PT P g ran d mast er, b o u n d ary, an d slave C lo cks 17.1.2. Advant ages of PT P One of the main advantages that P T P has over the Network Time Protocol (NTP) is hardware support present in various network interface controllers (NIC) and network switches. This specialized hardware allows P T P to account for delays in message transfer, and greatly improves the accuracy of time synchronization. While it is possible to use non-PTP enabled hardware components within the network, this will often cause an increase in jitter or introduce an asymmetry in the delay resulting in synchronization inaccuracies, which add up with multiple non-PTP aware components used in the communication path. To achieve the best possible accuracy, it is recommended that all networking components between P T P clocks are P T P hardware enabled. Time synchronization in larger networks where not all of the networking hardware supports P T P might be better suited for NT P . With hardware P T P support, the NIC has its own on-board clock, which is used to time stamp the received and transmitted P T P messages. It is this on-board clock that is synchronized to the P T P master, and the computer's system clock is synchronized to the P T P hardware clock on the NIC. With software P T P support, the system clock is used to time stamp the P T P messages and it is 280 Chapt er 1 7 . Configuring PT P Using pt p4 l synchronized to the P T P master directly. Hardware P T P support provides better accuracy since the NIC can time stamp the P T P packets at the exact moment they are sent and received while software P T P support requires additional processing of the P T P packets by the operating system. 17.2. Using PT P In order to use P T P , the kernel network driver for the intended interface has to support either software or hardware time stamping capabilities. 17.2.1. Checking for Driver and Hardware Support In addition to hardware time stamping support being present in the driver, the NIC must also be capable of supporting this functionality in the physical hardware. The best way to verify the time stamping capabilities of a particular driver and NIC is to use the et h t o o l utility to query the interface as follows: ~]# ethto o l -T eth3 Time stamping parameters for eth3: Capabilities: hardware-transmit (SOF_TIMESTAMPING_TX_HARDWARE) software-transmit (SOF_TIMESTAMPING_TX_SOFTWARE) hardware-receive (SOF_TIMESTAMPING_RX_HARDWARE) software-receive (SOF_TIMESTAMPING_RX_SOFTWARE) software-system-clock (SOF_TIMESTAMPING_SOFTWARE) hardware-raw-clock (SOF_TIMESTAMPING_RAW_HARDWARE) PTP Hardware Clock: 0 Hardware Transmit Timestamp Modes: off (HWTSTAMP_TX_OFF) on (HWTSTAMP_TX_ON) Hardware Receive Filter Modes: none (HWTSTAMP_FILTER_NONE) all (HWTSTAMP_FILTER_ALL) Where eth3 is the interface you want to check. For software time stamping support, the parameters list should include: SO F_T IMEST AMP ING _SO FT WAR E SO F_T IMEST AMP ING _T X_SO FT WAR E SO F_T IMEST AMP ING _R X_SO FT WAR E For hardware time stamping support, the parameters list should include: SO F_T IMEST AMP ING _R AW_HAR D WAR E SO F_T IMEST AMP ING _T X_HAR D WAR E SO F_T IMEST AMP ING _R X_HAR D WAR E 17.2.2. Inst alling PT P The kernel in Red Hat Enterprise Linux includes support for P T P . User space support is provided by the tools in the lin u xp t p package. To install lin u xp t p , issue the following command as ro o t: 281 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# yum i nstal l l i nuxptp This will install p t p 4 l and p h c2sys. D o not run more than one service to set the system clock's time at the same time. If you intend to serve P T P time using NT P , see Section 17.7, “ Serving PTP Time with NTP” . 17.2.3. St art ing pt p4 l The p t p 4 l program can be started from the command line or it can be started as a service. When running as a service, options are specified in the /etc/sysco nfi g /ptp4 l file. Options required for use both by the service and on the command line should be specified in the /etc/ptp4 l . co nf file. The /etc/sysco nfi g /ptp4 l file includes the -f /etc/ptp4 l . co nf command line option, which causes the ptp4 l program to read the /etc/ptp4 l . co nf file and process the options it contains. The use of the /etc/ptp4 l . co nf is explained in Section 17.3, “ Specifying a Configuration File” . More information on the different p t p 4 l options and the configuration file settings can be found in the ptp4 l (8) man page. St art ing pt p4 l as a Se rvice To start p t p 4 l as a service, issue the following command as ro o t: ~]# systemctl start ptp4 l For more information on managing system services in Red Hat Enterprise Linux 7, see Chapter 8, Managing Services with systemd. Using pt p4 l Fro m T he Co m m and Line The p t p 4 l program tries to use hardware time stamping by default. To use p t p 4 l with hardware time stamping capable drivers and NICs, you must provide the network interface to use with the -i option. Enter the following command as ro o t: ~]# ptp4 l -i eth3 -m Where eth3 is the interface you want to configure. Below is example output from p t p 4 l when the P T P clock on the NIC is synchronized to a master: ~]# ptp4 l -i eth3 -m selected eth3 as PTP clock port 1: INITIALIZING to LISTENING on INITIALIZE port 0: INITIALIZING to LISTENING on INITIALIZE port 1: new foreign master 00a069.fffe.0b552d-1 selected best master clock 00a069.fffe.0b552d port 1: LISTENING to UNCALIBRATED on RS_SLAVE master offset -23947 s0 freq +0 path delay 11350 master offset -28867 s0 freq +0 path delay 11236 master offset -32801 s0 freq +0 path delay 10841 master offset -37203 s1 freq +0 path delay 10583 master offset -7275 s2 freq -30575 path delay 10583 port 1: UNCALIBRATED to SLAVE on MASTER_CLOCK_SELECTED master offset -4552 s2 freq -30035 path delay 10385 The master offset value is the measured offset from the master in nanoseconds. The s0 , s1, s2 282 Chapt er 1 7 . Configuring PT P Using pt p4 l strings indicate the different clock servo states: s0 is unlocked, s1 is clock step and s2 is locked. Once the servo is in the locked state (s2), the clock will not be stepped (only slowly adjusted) unless the pi _o ffset_co nst option is set to a positive value in the configuration file (described in the ptp4 l (8) man page). The ad j value is the frequency adjustment of the clock in parts per billion (ppb). The path delay value is the estimated delay of the synchronization messages sent from the master in nanoseconds. Port 0 is a Unix domain socket used for local P T P management. Port 1 is the eth3 interface (based on the example above.) INITIALIZ ING, LISTENING, UNCALIBRATED and SLAVE are some of possible port states which change on the INITIALIZ E, RS_SLAVE, MASTER_CLOCK_SELECTED events. In the last state change message, the port state changed from UNCALIBRATED to SLAVE indicating successful synchronization with a P T P master clock. Lo gging Me ssage s Fro m pt p4 l By default, messages are sent to /var/l o g /messag es. However, specifying the -m option enables logging to standard output which can be useful for debugging purposes. To enable software time stamping, the -S option needs to be used as follows: ~]# ptp4 l -i eth3 -m -S 1 7 .2 .3.1 . Se le ct ing a De lay Me asure m e nt Me chanism There are two different delay measurement mechanisms and they can be selected by means of an option added to the ptp4 l command as follows: -P The -P selects the peer-to-peer (P2P) delay measurement mechanism. The P2P mechanism is preferred as it reacts to changes in the network topology faster, and may be more accurate in measuring the delay, than other mechanisms. The P2P mechanism can only be used in topologies where each port exchanges PTP messages with at most one other P2P port. It must be supported and used by all hardware, including transparent clocks, on the communication path. -E The -E selects the end-to-end (E2E) delay measurement mechanism. This is the default. The E2E mechanism is also referred to as the delay “ request-response” mechanism. -A The -A enables automatic selection of the delay measurement mechanism. The automatic option starts p t p 4 l in E2E mode. It will change to P2P mode if a peer delay request is received. Note All clocks on a single P T P communication path must use the same mechanism to measure the delay. Warnings will be printed in the following circumstances: When a peer delay request is received on a port using the E2E mechanism. When a E2E delay request is received on a port using the P2P mechanism. 283 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 17.3. Specifying a Configurat ion File The command line options and other options, which cannot be set on the command line, can be set in an optional configuration file. No configuration file is read by default, so it needs to be specified at runtime with the -f option. For example: ~]# ptp4 l -f /etc/ptp4 l . co nf A configuration file equivalent to the -i eth3 -m -S options shown above would look as follows: ~]# cat /etc/ptp4 l . co nf [global] verbose 1 time_stamping software [eth3] 17.4 . Using t he PT P Management Client The P T P management client, p mc, can be used to obtain additional information from p t p 4 l as follows: ~]# pmc -u -b 0 ' G ET C UR R ENT _D AT A_SET ' sending: GET CURRENT_DATA_SET 90e2ba.fffe.20c7f8-0 seq 0 RESPONSE MANAGMENT CURRENT_DATA_SET stepsRemoved 1 offsetFromMaster -142.0 meanPathDelay 9310.0 ~]# pmc -u -b 0 ' G ET T IME_ST AT US_NP ' sending: GET TIME_STATUS_NP 90e2ba.fffe.20c7f8-0 seq 0 RESPONSE MANAGMENT TIME_STATUS_NP master_offset 310 ingress_time 1361545089345029441 cumulativeScaledRateOffset +1.000000000 scaledLastGmPhaseChange 0 gmTimeBaseIndicator 0 lastGmPhaseChange 0x0000'0000000000000000.0000 gmPresent true gmIdentity 00a069.fffe.0b552d Setting the -b option to zero limits the boundary to the locally running p t p 4 l instance. A larger boundary value will retrieve the information also from P T P nodes further from the local clock. The retrievable information includes: stepsR emo ved is the number of communication paths to the grandmaster clock. o ffsetFro mMaster and master_offset is the last measured offset of the clock from the master in nanoseconds. meanP athD el ay is the estimated delay of the synchronization messages sent from the master in nanoseconds. 284 Chapt er 1 7 . Configuring PT P Using pt p4 l if g mP resent is true, the P T P clock is synchronized to a master, the local clock is not the grandmaster clock. g mId enti ty is the grandmaster's identity. For a full list of p mc commands, type the following as ro o t: ~]# pmc hel p Additional information is available in the pmc(8) man page. 17.5. Synchroniz ing t he Clocks The p h c2sys program is used to synchronize the system clock to the P T P hardware clock (PHC) on the NIC. The p h c2sys service is configured in the /etc/sysco nfi g /phc2sys configuration file. The default setting in the /etc/sysco nfi g /phc2sys file is as follows: OPTIONS="-a -r" The -a option causes p h c2sys to read the clocks to be synchronized from the p t p 4 l application. It will follow changes in the P T P port states, adjusting the synchronization between the NIC hardware clocks accordingly. The system clock is not synchronized, unless the -r option is also specified. If you want the system clock to be eligible to become a time source, specify the -r option twice. After making changes to /etc/sysco nfi g /phc2sys, restart the p h c2sys service from the command line by issuing a command as ro o t: ~]# systemctl restart phc2sys Under normal circumstances, use systemctl commands to start, stop, and restart the p h c2sys service. When you do not want to start p h c2sys as a service, you can start it from the command line. For example, enter the following command as ro o t: ~]# phc2sys -a -r The -a option causes p h c2sys to read the clocks to be synchronized from the p t p 4 l application. If you want the system clock to be eligible to become a time source, specify the -r option twice. Alternately, use the -s option to synchronize the system clock to a specific interface's P T P hardware clock. For example: ~]# phc2sys -s eth3 -w The -w option waits for the running p t p 4 l application to synchronize the P T P clock and then retrieves the TAI to UTC offset from p t p 4 l. Normally, P T P operates in the International Atomic Time (TAI) timescale, while the system clock is kept in Coordinated Universal Time (UTC). The current offset between the TAI and UTC timescales is 35 seconds. The offset changes when leap seconds are inserted or deleted, which typically happens every few years. The -O option needs to be used to set this offset manually when the -w is not used, as follows: 285 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# phc2sys -s eth3 -O -35 Once the p h c2sys servo is in a locked state, the clock will not be stepped, unless the -S option is used. This means that the p h c2sys program should be started after the p t p 4 l program has synchronized the P T P hardware clock. However, with -w, it is not necessary to start p h c2sys after p t p 4 l as it will wait for it to synchronize the clock. The p h c2sys program can also be started as a service by running: ~]# systemctl start phc2sys When running as a service, options are specified in the /etc/sysco nfi g /phc2sys file. More information on the different p h c2sys options can be found in the phc2sys(8) man page. Note that the examples in this section assume the command is run on a slave system or slave port. 17.6. Verifying T ime Synchroniz at ion When P T P time synchronization is working properly, new messages with offsets and frequency adjustments will be printed periodically to the p t p 4 l and p h c2sys (if hardware time stamping is used) outputs. These values will eventually converge after a short period of time. These messages can be seen in /var/l o g /messag es file. An example of the output follows: ptp4l[352.359]: ptp4l[352.361]: ptp4l[352.361]: ptp4l[353.210]: ptp4l[357.214]: ptp4l[357.214]: ptp4l[359.224]: 9202 ptp4l[360.224]: 9202 ptp4l[361.224]: 9202 ptp4l[361.224]: ptp4l[362.223]: 9202 ptp4l[363.223]: 8972 ptp4l[364.223]: 9153 ptp4l[365.223]: 9153 ptp4l[366.223]: 9169 ptp4l[367.222]: 9169 ptp4l[368.223]: 9170 ptp4l[369.235]: 9196 ptp4l[370.235]: 9238 286 selected /dev/ptp0 as PTP clock port 1: INITIALIZING to LISTENING on INITIALIZE port 0: INITIALIZING to LISTENING on INITIALIZE port 1: new foreign master 00a069.fffe.0b552d-1 selected best master clock 00a069.fffe.0b552d port 1: LISTENING to UNCALIBRATED on RS_SLAVE master offset 3304 s0 freq +0 path delay master offset 3708 s1 freq -29492 path delay master offset -3145 s2 freq -32637 path delay port 1: UNCALIBRATED to SLAVE on MASTER_CLOCK_SELECTED master offset -145 s2 freq -30580 path delay master offset 1043 s2 freq -29436 path delay master offset 266 s2 freq -29900 path delay master offset 430 s2 freq -29656 path delay master offset 615 s2 freq -29342 path delay master offset -191 s2 freq -29964 path delay master offset 466 s2 freq -29364 path delay master offset 24 s2 freq -29666 path delay master offset -375 s2 freq -30058 path delay Chapt er 1 7 . Configuring PT P Using pt p4 l ptp4l[371.235]: master offset 9199 ptp4l[372.235]: master offset 9204 285 s2 freq -29511 path delay -78 s2 freq -29788 path delay An example of the p h c2sys output follows: phc2sys[526.527]: phc2sys[527.528]: phc2sys[528.528]: phc2sys[529.528]: phc2sys[530.528]: phc2sys[531.528]: phc2sys[532.528]: phc2sys[533.528]: phc2sys[534.528]: phc2sys[535.529]: phc2sys[536.529]: phc2sys[537.529]: phc2sys[538.529]: phc2sys[539.529]: phc2sys[540.529]: phc2sys[541.529]: phc2sys[542.529]: phc2sys[543.529]: phc2sys[544.530]: phc2sys[545.530]: phc2sys[546.530]: Waiting for ptp4l... Waiting for ptp4l... phc offset 55341 s0 freq phc offset 54658 s1 freq phc offset 888 s2 freq phc offset 1156 s2 freq phc offset 411 s2 freq phc offset -73 s2 freq phc offset 39 s2 freq phc offset 95 s2 freq phc offset -359 s2 freq phc offset -257 s2 freq phc offset 119 s2 freq phc offset 288 s2 freq phc offset -149 s2 freq phc offset -352 s2 freq phc offset 166 s2 freq phc offset 50 s2 freq phc offset -31 s2 freq phc offset -333 s2 freq phc offset 194 s2 freq +0 -37690 -36802 -36268 -36666 -37026 -36936 -36869 -37294 -37300 -37001 -36796 -37147 -37395 -36982 -37048 -37114 -37426 -36999 delay delay delay delay delay delay delay delay delay delay delay delay delay delay delay delay delay delay delay 2729 2725 2756 2766 2738 2764 2746 2733 2738 2753 2745 2766 2760 2771 2748 2756 2748 2747 2749 For p t p 4 l there is also a directive, summary_i nterval , to reduce the output and print only statistics, as normally it will print a message every second or so. For example, to reduce the output to every 10 24 seconds, add the following line to the /etc/ptp4 l . co nf file: summary_interval 10 An example of the p t p 4 l output, with summary_i nterval 6 , follows: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: ptp4l: [615.253] selected /dev/ptp0 as PTP clock [615.255] port 1: INITIALIZING to LISTENING on INITIALIZE [615.255] port 0: INITIALIZING to LISTENING on INITIALIZE [615.564] port 1: new foreign master 00a069.fffe.0b552d-1 [619.574] selected best master clock 00a069.fffe.0b552d [619.574] port 1: LISTENING to UNCALIBRATED on RS_SLAVE [623.573] port 1: UNCALIBRATED to SLAVE on MASTER_CLOCK_SELECTED [684.649] rms 669 max 3691 freq -29383 ± 3735 delay 9232 ± 122 [748.724] rms 253 max 588 freq -29787 ± 221 delay 9219 ± 158 [812.793] rms 287 max 673 freq -29802 ± 248 delay 9211 ± 183 [876.853] rms 226 max 534 freq -29795 ± 197 delay 9221 ± 138 [940.925] rms 250 max 562 freq -29801 ± 218 delay 9199 ± 148 [1004.988] rms 226 max 525 freq -29802 ± 196 delay 9228 ± 143 [1069.065] rms 300 max 646 freq -29802 ± 259 delay 9214 ± 176 [1133.125] rms 226 max 505 freq -29792 ± 197 delay 9225 ± 159 [1197.185] rms 244 max 688 freq -29790 ± 211 delay 9201 ± 162 To reduce the output from the p h c2sys, it can be called it with the -u option as follows: 287 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# phc2sys -u summary-updates Where summary-updates is the number of clock updates to include in summary statistics. An example follows: ~]# phc2sys -s eth3 -w -m -u 6 0 phc2sys[700.948]: rms 1837 max 10123 freq -36474 ± 4752 delay 2752 ± 16 phc2sys[760.954]: rms 194 max 457 freq -37084 ± 174 delay 2753 ± 12 phc2sys[820.963]: rms 211 max 487 freq -37085 ± 185 delay 2750 ± 19 phc2sys[880.968]: rms 183 max 440 freq -37102 ± 164 delay 2734 ± 91 phc2sys[940.973]: rms 244 max 584 freq -37095 ± 216 delay 2748 ± 16 phc2sys[1000.979]: rms 220 max 573 freq -36666 ± 182 delay 2747 ± 43 phc2sys[1060.984]: rms 266 max 675 freq -36759 ± 234 delay 2753 ± 17 17.7. Serving PT P T ime wit h NT P The ntpd daemon can be configured to distribute the time from the system clock synchronized by p t p 4 l or p h c2sys by using the LOCAL reference clock driver. To prevent ntpd from adjusting the system clock, the ntp. co nf file must not specify any NT P servers. The following is a minimal example of ntp. co nf: ~]# cat /etc/ntp. co nf server 127.127.1.0 fudge 127.127.1.0 stratum 0 Note When the D HC P client program, d h clien t , receives a list of NT P servers from the D HC P server, it adds them to ntp. co nf and restarts the service. To disable that feature, add P EER NT P = no to /etc/sysco nfi g /netwo rk. 17.8. Serving NT P T ime wit h PT P NT P to P T P synchronization in the opposite direction is also possible. When ntpd is used to synchronize the system clock, p t p 4 l can be configured with the pri o ri ty1 option (or other clock options included in the best master clock algorithm) to be the grandmaster clock and distribute the time from the system clock via P T P : ~]# cat /etc/ptp4 l . co nf [global] priority1 127 [eth3] # ptp4l -f /etc/ptp4l.conf With hardware time stamping, p h c2sys needs to be used to synchronize the P T P hardware clock to the system clock. If running p h c2sys as a service, edit the /etc/sysco nfi g /phc2sys configuration file. The default setting in the /etc/sysco nfi g /phc2sys file is as follows: OPTIONS="-a -r" 288 Chapt er 1 7 . Configuring PT P Using pt p4 l As ro o t, edit that line as follows: ~]# vi /etc/sysco nfi g /phc2sys OPTIONS="-a -r -r" The -r option is used twice here to allow synchronization of the P T P hardware clock on the NIC from the system clock. Restart the p h c2sys service for the changes to take effect: ~]# systemctl restart phc2sys To prevent quick changes in the P T P clock's frequency, the synchronization to the system clock can be loosened by using smaller P (proportional) and I (integral) constants for the PI servo: ~]# phc2sys -a -r -r -P 0 . 0 1 -I 0 . 0 0 0 1 17.9. Synchroniz e t o PT P or NT P T ime Using t imemast er When there are multiple P T P domains available on the network, or fallback to NT P is needed, the t imemast er program can be used to synchronize the system clock to all available time sources. The P T P time is provided by p h c2sys and p t p 4 l via shared memory driver (SHM reference clocks to chro nyd or ntpd (depending on the NT P daemon that has been configured on the system). The NT P daemon can then compare all time sources, both P T P and NT P , and use the best sources to synchronize the system clock. On start, t imemast er reads a configuration file that specifies the NT P and P T P time sources, checks which network interfaces have their own or share a P T P hardware clock (PHC), generates configuration files for p t p 4 l and chro nyd or ntpd , and starts the p t p 4 l, p h c2sys, and chro nyd or ntpd processes as needed. It will remove the generated configuration files on exit. It writes configuration files for chro nyd , ntpd , and p t p 4 l to /var/run/ti memaster/. 17.9.1. St art ing t imemast er as a Service To start t imemast er as a service, issue the following command as ro o t: ~]# systemctl start ti memaster This will read the options in /etc/ti memaster. co nf. For more information on managing system services in Red Hat Enterprise Linux 7, see Chapter 8, Managing Services with systemd. 17.9.2. Underst anding t he t imemast er Configurat ion File Red Hat Enterprise Linux provides a default /etc/ti memaster. co nf file with a number of sections containing default options. The section headings are enclosed in brackets. To view the default configuration, issue a command as follows: ~]$ l ess /etc/ti memaster. co nf # Configuration file for timemaster #[ntp_server ntp-server.local] #minpoll 4 #maxpoll 4 289 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide #[ptp_domain 0] #interfaces eth0 [timemaster] ntp_program chronyd [chrony.conf] include /etc/chrony.conf [ntp.conf] includefile /etc/ntp.conf [ptp4l.conf] [chronyd] path /usr/sbin/chronyd options -u chrony [ntpd] path /usr/sbin/ntpd options -u ntp:ntp -g [phc2sys] path /usr/sbin/phc2sys [ptp4l] path /usr/sbin/ptp4l Notice the section named as follows: [ntp_server address] This is an example of an NT P server section, “ ntp-server.local” is an example of a host name for an NT P server on the local LAN. Add more sections as required using a host name or IP address as part of the section name. Note that the short polling values in that example section are not suitable for a public server, see Chapter 16, Configuring NTP Using ntpd for an explanation of suitable mi npo l l and maxpo l l values. Notice the section named as follows: [ptp_domain number] A “ PTP domain” is a group of one or more P T P clocks that synchronize to each other. They may or may not be synchronized to clocks in another domain. Clocks that are configured with the same domain number make up the domain. This includes a P T P grandmaster clock. The domain number in each “ PTP domain” section needs to correspond to one of the P T P domains configured on the network. An instance of p t p 4 l is started for every interface which has its own P T P clock and hardware time stamping is enabled automatically. Interfaces that support hardware time stamping have a P T P clock (PHC) attached, however it is possible for a group of interfaces on a NIC to share a PHC. A separate p t p 4 l instance will be started for each group of interfaces sharing the same PHC and for each interface that supports only software time stamping. All p t p 4 l instances are configured to run as a slave. If an interface with hardware time stamping is specified in more than one P T P domain, then only the first p t p 4 l instance created will have hardware time stamping enabled. 290 Chapt er 1 7 . Configuring PT P Using pt p4 l Notice the section named as follows: [timemaster] The default t imemast er configuration includes the system ntpd and chrony configuration (/etc/ntp. co nf or /etc/chro nyd . co nf) in order to include the configuration of access restrictions and authentication keys. That means any NT P servers specified there will be used with t imemast er too. The section headings are as follows: [ntp_server ntp-server. l o cal ] — Specify polling intervals for this server. Create additional sections as required. Include the host name or IP address in the section heading. [ptp_d o mai n 0 ] — Specify interfaces that have P T P clocks configured for this domain. Create additional sections with, the appropriate domain number, as required. [ti memaster] — Specify the NT P daemon to be used. Possible values are chro nyd and ntpd . [chro ny. co nf] — Specify any additional settings to be copied to the configuration file generated for chro nyd . [ntp. co nf] — Specify any additional settings to be copied to the configuration file generated for ntpd . [ptp4 l . co nf] — Specify options to be copied to the configuration file generated for p t p 4 l. [chro nyd ] — Specify any additional settings to be passed on the command line to chro nyd . [ntpd ] — Specify any additional settings to be passed on the command line to ntpd . [phc2sys] — Specify any additional settings to be passed on the command line to p h c2sys. [ptp4 l ] — Specify any additional settings to be passed on the command line to all instances of p t p 4 l. The section headings and there contents are explained in detail in the ti memaster(8) manual page. 17.9.3. Configuring t imemast er Opt ions Pro ced u re 17.1. Ed it in g t h e t imemast er C o n f ig u rat io n File 1. To change the default configuration, open the /etc/ti memaster. co nf file for editing as ro o t: ~]# vi /etc/ti memaster. co nf 2. For each NT P server you want to control using t imemast er, create [ntp_server address] sections . Note that the short polling values in the example section are not suitable for a public server, see Chapter 16, Configuring NTP Using ntpd for an explanation of suitable mi npo l l and maxpo l l values. 3. To add interfaces that should be used in a domain, edit the #[ptp_d o mai n 0 ] section and add the interfaces. Create additional domains as required. For example: [ptp_domain 0] interfaces eth0 291 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide [ptp_domain 1] interfaces eth1 4. If required to use ntpd as the NT P daemon on this system, change the default entry in the [ti memaster] section from chro nyd to ntpd . See Chapter 15, Configuring NTP Using the chrony Suite for information on the differences between ntpd and chronyd. 5. If using chro nyd as the NT P server on this system, add any additional options below the default i ncl ud e /etc/chro ny. co nf entry in the [chro ny. co nf] section. Edit the default i ncl ud e entry if the path to /etc/chro ny. co nf is known to have changed. 6. If using ntpd as the NT P server on this system, add any additional options below the default i ncl ud e /etc/ntp. co nf entry in the [ntp. co nf] section. Edit the default i ncl ud e entry if the path to /etc/ntp. co nf is known to have changed. 7. In the [ptp4 l . co nf] section, add any options to be copied to the configuration file generated for p t p 4 l. This chapter documents common options and more information is available in the ptp4 l (8) manual page. 8. In the [chro nyd ] section, add any command line options to be passed to chro nyd when called by t imemast er. See Chapter 15, Configuring NTP Using the chrony Suite for information on using chro nyd . 9. In the [ntpd ] section, add any command line options to be passed to ntpd when called by t imemast er. See Chapter 16, Configuring NTP Using ntpd for information on using ntpd . 10. In the [phc2sys] section, add any command line options to be passed to p h c2sys when called by t imemast er. This chapter documents common options and more information is available in the phy2sys(8) manual page. 11. In the [ptp4 l ] section, add any command line options to be passed to p t p 4 l when called by t imemast er. This chapter documents common options and more information is available in the ptp4 l (8) manual page. 12. Save the configuration file and restart t imemast er by issuing the following command as ro o t: ~]# systemctl restart ti memaster 17.10. Improving Accuracy Previously, test results indicated that disabling the tickless kernel capability could significantly improve the stability of the system clock, and thus improve the P T P synchronization accuracy (at the cost of increased power consumption). The kernel tickless mode can be disabled by adding no hz= o ff to the kernel boot option parameters. However, recent improvements applied to kernel 3. 10 . 0 -19 7. el 7 have greatly improved the stability of the system clock and the difference in stability of the clock with and without no hz= o ff should be much smaller now for most users. The p t p 4 l and p h c2sys applications can be configured to use a new adaptive servo. The advantage over the PI servo is that it does not require configuration of the PI constants to perform well. To make use of this for p t p 4 l, add the following line to the /etc/ptp4 l . co nf file: clock_servo linreg 292 Chapt er 1 7 . Configuring PT P Using pt p4 l After making changes to /etc/ptp4 l . co nf, restart the p t p 4 l service from the command line by issuing the following command as ro o t: ~]# systemctl restart ptp4 l To make use of this for p h c2sys, add the following line to the /etc/sysco nfi g /phc2sys file: -E linreg After making changes to /etc/sysco nfi g /phc2sys, restart the p h c2sys service from the command line by issuing the following command as ro o t: ~]# systemctl restart phc2sys 17.11. Addit ional Resources The following sources of information provide additional resources regarding P T P and the p t p 4 l tools. 17.11.1. Inst alled Document at ion ptp4 l (8) man page — D escribes p t p 4 l options including the format of the configuration file. pmc(8) man page — D escribes the P T P management client and its command options. phc2sys(8) man page — D escribes a tool for synchronizing the system clock to a P T P hardware clock (PHC). ti memaster(8) man page — D escribes a program that uses p t p 4 l and p h c2sys to synchronize the system clock using chro nyd or ntpd . 17.11.2. Useful Websit es h t t p ://www.n ist .g o v/el/isd /ieee/ieee1588.cf m The IEEE 1588 Standard. 293 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Part VI. Monitoring and Automation This part describes various tools that allow system administrators to monitor system performance, automate system tasks, and report bugs. 294 Chapt er 1 8 . Syst em Monit oring T ools Chapter 18. System Monitoring Tools In order to configure the system, system administrators often need to determine the amount of free memory, how much free disk space is available, how the hard drive is partitioned, or what processes are running. 18.1. Viewing Syst em Processes 18.1.1. Using t he ps Command The ps command allows you to display information about running processes. It produces a static list, that is, a snapshot of what is running when you execute the command. If you want a constantly updated list of running processes, use the to p command or the Syst em Mo n it o r application instead. To list all processes that are currently running on the system including processes owned by other users, type the following at a shell prompt: ps ax For each listed process, the ps ax command displays the process ID (P ID ), the terminal that is associated with it (T T Y ), the current status (ST AT ), the cumulated CPU time (T IME), and the name of the executable file (C O MMAND ). For example: ~]$ ps ax PID TTY STAT 1 ? Ss --deserialize 23 2 ? S 3 ? S 5 ? S> [output truncated] TIME COMMAND 0:01 /usr/lib/systemd/systemd --switched-root --system 0:00 [kthreadd] 0:00 [ksoftirqd/0] 0:00 [kworker/0:0H] To display the owner alongside each process, use the following command: ps aux Apart from the information provided by the ps ax command, ps aux displays the effective user name of the process owner (USER ), the percentage of the CPU (%C P U) and memory (%MEM) usage, the virtual memory size in kilobytes (VSZ), the non-swapped physical memory size in kilobytes (R SS), and the time or date the process was started. For example: ~]$ ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME root 1 0.3 0.3 134776 6840 ? Ss 09:28 0:01 /usr/lib/systemd/systemd --switched-root --system --d root 2 0.0 0.0 0 0 ? S 09:28 0:00 root 3 0.0 0.0 0 0 ? S 09:28 0:00 root 5 0.0 0.0 0 0 ? S> 09:28 0:00 [output truncated] COMMAND [kthreadd] [ksoftirqd/0] [kworker/0:0H] You can also use the ps command in a combination with g rep to see if a particular process is running. For example, to determine if Emacs is running, type: 295 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]$ ps ax | g rep emacs 12056 pts/3 S+ 0:00 emacs 12060 pts/2 S+ 0:00 grep --color=auto emacs For a complete list of available command line options, see the p s(1) manual page. 18.1.2. Using t he t op Command The to p command displays a real-time list of processes that are running on the system. It also displays additional information about the system uptime, current CPU and memory usage, or total number of running processes, and allows you to perform actions such as sorting the list or killing a process. To run the to p command, type the following at a shell prompt: to p For each listed process, the to p command displays the process ID (P ID ), the effective user name of the process owner (USER ), the priority (P R ), the nice value (NI), the amount of virtual memory the process uses (VIR T ), the amount of non-swapped physical memory the process uses (R ES), the amount of shared memory the process uses (SHR ), the process status field S), the percentage of the CPU (%C P U) and memory (%MEM) usage, the cumulated CPU time (T IME+ ), and the name of the executable file (C O MMAND ). For example: ~]$ to p top - 10:16:20 up 47 min, 2 users, load average: 0.06, 0.06, 0.06 Tasks: 159 total, 3 running, 156 sleeping, 0 stopped, 0 zombie %Cpu(s): 19.5 us, 3.0 sy, 0.0 ni, 77.5 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem: 1885320 total, 947172 used, 938148 free, 824 buffers KiB Swap: 839676 total, 0 used, 839676 free. 410120 cached Mem PID USER PR COMMAND 3199 sjw 20 shell 1412 root 20 3275 sjw 20 nautilus 3576 sjw 20 terminal755 root 20 vdagentd 4118 root 20 kworker/0:0 [output truncated] NI VIRT RES SHR S %CPU %MEM TIME+ 0 1486868 207596 38044 S 15.3 11.0 0:48.72 gnome- 0 0 186784 922504 35668 25796 7416 R 15616 S 4.3 1.0 1.9 1.4 0:06.71 Xorg 0:00.44 0 562108 23384 13068 S 1.0 1.2 0:01.55 gnome- 0 20196 804 620 S 0.3 0.0 0:00.27 spice- 0 0 0 0 S 0.3 0.0 0:00.64 Table 18.1, “ Interactive top commands” contains useful interactive commands that you can use with to p. For more information, see the t o p (1) manual page. T ab le 18.1. In t eract ive t o p co mman d s 296 Chapt er 1 8 . Syst em Monit oring T ools C o mman d D escrip t io n Enter, Space h h, ? k Immediately refreshes the display. D isplays a help screen for interactive commands. D isplays a help screen for windows and field groups. Kills a process. You are prompted for the process ID and the signal to send to it. Changes the number of displayed processes. You are prompted to enter the number. Sorts the list by user. Sorts the list by memory usage. Sorts the list by CPU usage. Terminates the utility and returns to the shell prompt. n u M P q 18.1.3. Using t he Syst em Monit or T ool The P ro cesses tab of the Syst em Mo n it o r tool allows you to view, search for, change the priority of, and kill processes from the graphical user interface. To start the Syst em Mo n it o r tool from the command line, type g no me-system-mo ni to r at a shell prompt. The Syst em Mo n it o r tool appears. Alternatively, if using the GNOME desktop, press the Super key to enter the Activities Overview, type System Mo ni to r and then press Enter. The Syst em Mo n it o r tool appears. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. Click the P ro cesses tab to view the list of running processes. Fig u re 18.1. Syst em Mo n it o r — Pro cesses For each listed process, the Syst em Mo n it o r tool displays its name (P ro cess Name), current status (Status), percentage of the CPU usage (% C P U), nice value (Ni ce), process ID (ID ), memory 297 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide usage (Memo ry), the channel the process is waiting in (Wai ti ng C hannel ), and additional details about the session (Sessi o n). To sort the information by a specific column in ascending order, click the name of that column. Click the name of the column again to toggle the sort between ascending and descending order. By default, the Syst em Mo n it o r tool displays a list of processes that are owned by the current user. Selecting various options from the View menu allows you to: view only active processes, view all processes, view your processes, view process dependencies, Additionally, two buttons enable you to: refresh the list of processes, end a process by selecting it from the list and then clicking the End P ro cess button. 18.2. Viewing Memory Usage 18.2.1. Using t he free Command The free command allows you to display the amount of free and used memory on the system. To do so, type the following at a shell prompt: free The free command provides information about both the physical memory (Mem) and swap space (Swap). It displays the total amount of memory (to tal ), as well as the amount of memory that is in use (used ), free (free), shared (shared ), in kernel buffers (buffers), and cached (cached ). For example: ~]$ free total Mem: 760752 -/+ buffers/cache: Swap: 1540088 used 661332 337656 283652 free 99420 423096 1256436 shared 0 buffers 6476 cached 317200 By default, free displays the values in kilobytes. To display the values in megabytes, supply the -m command line option: free -m For instance: ~]$ free -m total Mem: 742 309 -/+ buffers/cache: Swap: 1503 298 used 646 free 96 330 276 412 1227 shared 0 buffers 6 cached Chapt er 1 8 . Syst em Monit oring T ools For a complete list of available command line options, see the f ree(1) manual page. 18.2.2. Using t he Syst em Monit or T ool The R eso urces tab of the Syst em Mo n it o r tool allows you to view the amount of free and used memory on the system. To start the Syst em Mo n it o r tool from the command line, type g no me-system-mo ni to r at a shell prompt. The Syst em Mo n it o r tool appears. Alternatively, if using the GNOME desktop, press the Super key to enter the Activities Overview, type System Mo ni to r and then press Enter. The Syst em Mo n it o r tool appears. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. Click the R eso urces tab to view the system's memory usage. Fig u re 18.2. Syst em Mo n it o r — R eso u rces In the Memo ry and Swap Hi sto ry section, the Syst em Mo n it o r tool displays a graphical representation of the memory and swap usage history, as well as the total amount of the physical memory (Memo ry) and swap space (Swap) and how much of it is in use. 18.3. Viewing CPU Usage 18.3.1. Using t he Syst em Monit or T ool The R eso urces tab of the Syst em Mo n it o r tool allows you to view the current CPU usage on the system. To start the Syst em Mo n it o r tool from the command line, type g no me-system-mo ni to r at a shell prompt. The Syst em Mo n it o r tool appears. Alternatively, if using the GNOME desktop, press the Super key to enter the Activities Overview, type System Mo ni to r and then press Enter. The 299 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Syst em Mo n it o r tool appears. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. Click the R eso urces tab to view the system's CPU usage. In the C P U Hi sto ry section, the Syst em Mo n it o r tool displays a graphical representation of the CPU usage history and shows the percentage of how much CPU is currently in use. 18.4 . Viewing Block Devices and File Syst ems 18.4 .1. Using t he lsblk Command The l sbl k command allows you to display a list of available block devices. It provides more information and better control on output formatting than the bl ki d command. It reads information from u d ev, therefore it is usable by non-ro o t users. To display a list of block devices, type the following at a shell prompt: l sbl k For each listed block device, the l sbl k command displays the device name (NAME), major and minor device number (MAJ: MIN), if the device is removable (R M), its size (SIZE), if the device is readonly (R O ), what type it is (T Y P E), and where the device is mounted (MO UNT P O INT ). For example: ~]$ l sbl k NAME MAJ:MIN RM SIZE RO TYPE sr0 11:0 1 1024M 0 rom vda 252:0 0 20G 0 rom |-vda1 252:1 0 500M 0 part `-vda2 252:2 0 19.5G 0 part |-vg_kvm-lv_root (dm-0) 253:0 0 18G 0 lvm `-vg_kvm-lv_swap (dm-1) 253:1 0 1.5G 0 lvm MOUNTPOINT /boot / [SWAP] By default, l sbl k lists block devices in a tree-like format. To display the information as an ordinary list, add the -l command line option: l sbl k -l For instance: ~]$ l sbl k -l NAME MAJ:MIN RM SIZE RO TYPE sr0 11:0 1 1024M 0 rom vda 252:0 0 20G 0 rom vda1 252:1 0 500M 0 part vda2 252:2 0 19.5G 0 part vg_kvm-lv_root (dm-0) 253:0 0 18G 0 lvm vg_kvm-lv_swap (dm-1) 253:1 0 1.5G 0 lvm MOUNTPOINT /boot / [SWAP] For a complete list of available command line options, see the lsb lk(8) manual page. 18.4 .2. Using t he blkid Command 300 Chapt er 1 8 . Syst em Monit oring T ools The bl ki d command allows you to display low-level information about available block devices. It requires ro o t privileges, therefore non-ro o t users should use the l sbl k command. To do so, type the following at a shell prompt as ro o t: bl ki d For each listed block device, the bl ki d command displays available attributes such as its universally unique identifier (UUID ), file system type (T Y P E), or volume label (LABEL). For example: ~]# bl ki d /dev/vda1: UUID="7fa9c421-0054-4555-b0ca-b470a97a3d84" TYPE="ext4" /dev/vda2: UUID="7IvYzk-TnnK-oPjf-ipdD-cofz-DXaJ-gPdgBW" TYPE="LVM2_member" /dev/mapper/vg_kvm-lv_root: UUID="a07b967c-71a0-4925-ab02-aebcad2ae824" TYPE="ext4" /dev/mapper/vg_kvm-lv_swap: UUID="d7ef54ca-9c41-4de4-ac1b-4193b0c1ddb6" TYPE="swap" By default, the bl ki d command lists all available block devices. To display information about a particular device only, specify the device name on the command line: bl ki d device_name For instance, to display information about /d ev/vd a1, type as ro o t: ~]# bl ki d /d ev/vd a1 /dev/vda1: UUID="7fa9c421-0054-4555-b0ca-b470a97a3d84" TYPE="ext4" You can also use the above command with the -p and -o ud ev command line options to obtain more detailed information. Note that ro o t privileges are required to run this command: bl ki d -po ud ev device_name For example: ~]# bl ki d -po ud ev /d ev/vd a1 ID_FS_UUID=7fa9c421-0054-4555-b0ca-b470a97a3d84 ID_FS_UUID_ENC=7fa9c421-0054-4555-b0ca-b470a97a3d84 ID_FS_VERSION=1.0 ID_FS_TYPE=ext4 ID_FS_USAGE=filesystem For a complete list of available command line options, see the b lkid (8) manual page. 18.4 .3. Using t he findmnt Command The fi nd mnt command allows you to display a list of currently mounted file systems. To do so, type the following at a shell prompt: fi nd mnt For each listed file system, the fi nd mnt command displays the target mount point (T AR G ET ), source device (SO UR C E), file system type (FST Y P E), and relevant mount options (O P T IO NS). For example: 301 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]$ fi nd mnt TARGET OPTIONS / SOURCE FSTYPE /dev/mapper/rhel-root xfs rw,relatime,seclabel,attr2,inode64,noquota ├─/proc proc proc rw,nosuid,nodev,noexec,relatime │ ├─/proc/sys/fs/binfmt_misc systemd-1 autofs rw,relatime,fd=32,pgrp=1,timeout=300,minproto=5,maxproto=5,direct │ └─/proc/fs/nfsd sunrpc nfsd rw,relatime ├─/sys sysfs sysfs rw,nosuid,nodev,noexec,relatime,seclabel │ ├─/sys/kernel/security securityfs securityfs rw,nosuid,nodev,noexec,relatime │ ├─/sys/fs/cgroup tmpfs tmpfs rw,nosuid,nodev,noexec,seclabel,mode=755 [output truncated] By default, fi nd mnt lists file systems in a tree-like format. To display the information as an ordinary list, add the -l command line option: fi nd mnt -l For instance: ~]$ fi nd mnt -l TARGET SOURCE FSTYPE /proc proc proc rw,nosuid,nodev,noexec,relatime /sys sysfs sysfs rw,nosuid,nodev,noexec,relatime,seclabel /dev devtmpfs devtmpfs rw,nosuid,seclabel,size=933372k,nr_inodes=233343,mode=755 /sys/kernel/security securityfs securityfs rw,nosuid,nodev,noexec,relatime /dev/shm tmpfs tmpfs rw,nosuid,nodev,seclabel /dev/pts devpts devpts rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=000 /run tmpfs tmpfs rw,nosuid,nodev,seclabel,mode=755 /sys/fs/cgroup tmpfs tmpfs rw,nosuid,nodev,noexec,seclabel,mode=755 [output truncated] OPTIONS You can also choose to list only file systems of a particular type. To do so, add the -t command line option followed by a file system type: fi nd mnt -t type For example, to all list xfs file systems, type: 302 Chapt er 1 8 . Syst em Monit oring T ools ~]$ fi nd mnt -t xfs TARGET SOURCE FSTYPE OPTIONS / /dev/mapper/rhel-root xfs rw,relatime,seclabel,attr2,inode64,noquota └─/boot /dev/vda1 xfs rw,relatime,seclabel,attr2,inode64,noquota For a complete list of available command line options, see the f in d mn t (8) manual page. 18.4 .4 . Using t he df Command The d f command allows you to display a detailed report on the system's disk space usage. To do so, type the following at a shell prompt: df For each listed file system, the d f command displays its name (Fi l esystem), size (1K-bl o cks or Si ze), how much space is used (Used ), how much space is still available (Avai l abl e), the percentage of space usage (Use%), and where is the file system mounted (Mo unted o n). For example: ~]$ d f Filesystem 1K-blocks /dev/mapper/vg_kvm-lv_root 18618236 tmpfs 380376 /dev/vda1 495844 Used Available Use% Mounted on 4357360 13315112 25% / 288 380088 1% /dev/shm 77029 393215 17% /boot By default, the d f command shows the partition size in 1 kilobyte blocks and the amount of used and available disk space in kilobytes. To view the information in megabytes and gigabytes, supply the -h command line option, which causes d f to display the values in a human-readable format: d f -h For instance: ~]$ d f -h Filesystem /dev/mapper/vg_kvm-lv_root tmpfs /dev/vda1 Size 18G 372M 485M Used Avail Use% Mounted on 4.2G 13G 25% / 288K 372M 1% /dev/shm 76M 384M 17% /boot For a complete list of available command line options, see the d f (1) manual page. 18.4 .5. Using t he du Command The d u command allows you to displays the amount of space that is being used by files in a directory. To display the disk usage for each of the subdirectories in the current working directory, run the command with no additional command line options: du For example: 303 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]$ d u 14972 4 4 12 15004 ./Downloads ./.mozilla/extensions ./.mozilla/plugins ./.mozilla . By default, the d u command displays the disk usage in kilobytes. To view the information in megabytes and gigabytes, supply the -h command line option, which causes the utility to display the values in a human-readable format: d u -h For instance: ~]$ d u -h 15M ./Downloads 4.0K ./.mozilla/extensions 4.0K ./.mozilla/plugins 12K ./.mozilla 15M . At the end of the list, the d u command always shows the grand total for the current directory. To display only this information, supply the -s command line option: d u -sh For example: ~]$ d u -sh 15M . For a complete list of available command line options, see the d u (1) manual page. 18.4 .6. Using t he Syst em Monit or T ool The Fi l e Systems tab of the Syst em Mo n it o r tool allows you to view file systems and disk space usage in the graphical user interface. To start the Syst em Mo n it o r tool from the command line, type g no me-system-mo ni to r at a shell prompt. The Syst em Mo n it o r tool appears. Alternatively, if using the GNOME desktop, press the Super key to enter the Activities Overview, type System Mo ni to r and then press Enter. The Syst em Mo n it o r tool appears. The Super key appears in a variety of guises, depending on the keyboard and other hardware, but often as either the Windows or Command key, and typically to the left of the Spacebar. Click the Fi l e Systems tab to view a list of file systems. 304 Chapt er 1 8 . Syst em Monit oring T ools Fig u re 18.3. Syst em Mo n it o r — File Syst ems For each listed file system, the Syst em Mo n it o r tool displays the source device (D evi ce), target mount point (D i recto ry), and file system type (T ype), as well as its size (T o tal ), and how much space is available (Avai l abl e), and used (Used ). 18.5. Viewing Hardware Informat ion 18.5.1. Using t he lspci Command The l spci command allows you to display information about PCI buses and devices that are attached to them. To list all PCI devices that are in the system, type the following at a shell prompt: l spci This displays a simple list of devices, for example: ~]$ l spci 00:00.0 Host bridge: Intel Corporation 82X38/X48 Express DRAM Controller 00:01.0 PCI bridge: Intel Corporation 82X38/X48 Express Host-Primary PCI Express Bridge 00:1a.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #4 (rev 02) 00:1a.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #5 (rev 02) 00:1a.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #6 (rev 02) [output truncated] You can also use the -v command line option to display more verbose output, or -vv for very verbose output: l spci -v|-vv For instance, to determine the manufacturer, model, and memory size of a system's video card, type: ~]$ l spci -v [output truncated] 305 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 01:00.0 VGA compatible controller: nVidia Corporation G84 [Quadro FX 370] (rev a1) (prog-if 00 [VGA controller]) Subsystem: nVidia Corporation Device 0491 Physical Slot: 2 Flags: bus master, fast devsel, latency 0, IRQ 16 Memory at f2000000 (32-bit, non-prefetchable) [size=16M] Memory at e0000000 (64-bit, prefetchable) [size=256M] Memory at f0000000 (64-bit, non-prefetchable) [size=32M] I/O ports at 1100 [size=128] Expansion ROM at [disabled] Capabilities: Kernel driver in use: nouveau Kernel modules: nouveau, nvidiafb [output truncated] For a complete list of available command line options, see the lsp ci(8) manual page. 18.5.2. Using t he lsusb Command The l susb command allows you to display information about USB buses and devices that are attached to them. To list all USB devices that are in the system, type the following at a shell prompt: l susb This displays a simple list of devices, for example: ~]$ l susb Bus 001 Device 001: ID 1d6b:0002 Bus 002 Device 001: ID 1d6b:0002 [output truncated] Bus 001 Device 002: ID 0bda:0151 Device (Multicard Reader) Bus 008 Device 002: ID 03f0:2c24 Bus 008 Device 003: ID 04b3:3025 Linux Foundation 2.0 root hub Linux Foundation 2.0 root hub Realtek Semiconductor Corp. Mass Storage Hewlett-Packard Logitech M-UAL-96 Mouse IBM Corp. You can also use the -v command line option to display more verbose output: l susb -v For instance: ~]$ l susb -v [output truncated] Bus 008 Device 002: ID 03f0:2c24 Hewlett-Packard Logitech M-UAL-96 Mouse Device Descriptor: bLength 18 bDescriptorType 1 bcdUSB 2.00 bDeviceClass 0 (Defined at Interface level) bDeviceSubClass 0 bDeviceProtocol 0 306 Chapt er 1 8 . Syst em Monit oring T ools bMaxPacketSize0 8 idVendor 0x03f0 idProduct 0x2c24 bcdDevice 31.00 iManufacturer 1 iProduct 2 iSerial 0 bNumConfigurations 1 Configuration Descriptor: bLength bDescriptorType [output truncated] Hewlett-Packard Logitech M-UAL-96 Mouse 9 2 For a complete list of available command line options, see the lsu sb (8) manual page. 18.5.3. Using t he lscpu Command The l scpu command allows you to list information about CPUs that are present in the system, including the number of CPUs, their architecture, vendor, family, model, CPU caches, etc. To do so, type the following at a shell prompt: l scpu For example: ~]$ l scpu Architecture: CPU op-mode(s): Byte Order: CPU(s): On-line CPU(s) list: Thread(s) per core: Core(s) per socket: Socket(s): NUMA node(s): Vendor ID: CPU family: Model: Stepping: CPU MHz: BogoMIPS: Virtualization: L1d cache: L1i cache: L2 cache: NUMA node0 CPU(s): x86_64 32-bit, 64-bit Little Endian 4 0-3 1 4 1 1 GenuineIntel 6 23 7 1998.000 4999.98 VT-x 32K 32K 3072K 0-3 For a complete list of available command line options, see the lscp u (1) manual page. 18.6. Monit oring Performance wit h Net -SNMP 307 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Red Hat Enterprise Linux 7 includes the N et - SN MP software suite, which includes a flexible and extensible simple network management protocol (SNMP) agent. This agent and its associated utilities can be used to provide performance data from a large number of systems to a variety of tools which support polling over the SNMP protocol. This section provides information on configuring the Net-SNMP agent to securely provide performance data over the network, retrieving the data using the SNMP protocol, and extending the SNMP agent to provide custom performance metrics. 18.6.1. Inst alling Net -SNMP The Net-SNMP software suite is available as a set of RPM packages in the Red Hat Enterprise Linux software distribution. Table 18.2, “ Available Net-SNMP packages” summarizes each of the packages and their contents. T ab le 18.2. Availab le N et - SN MP p ackag es Packag e Pro vid es net-snmp The SNMP Agent D aemon and documentation. This package is required for exporting performance data. The netsnmp library and the bundled management information bases (MIBs). This package is required for exporting performance data. SNMP clients such as snmpg et and snmpwal k. This package is required in order to query a system's performance data over SNMP. The mi b2c utility and the NetSNMP Perl module. Note that this package is provided by the Optional channel. See Section 7.5.7, “ Adding the Optional and Supplementary Repositories” for more information on Red Hat additional channels. An SNMP client library for Python. Note that this package is provided by the Optional channel. See Section 7.5.7, “ Adding the Optional and Supplementary Repositories” for more information on Red Hat additional channels. net-snmp-libs net-snmp-utils net-snmp-perl net-snmp-python To install any of these packages, use the yum command in the following form: yum i nstal l package… For example, to install the SNMP Agent D aemon and SNMP clients used in the rest of this section, type the following at a shell prompt as ro o t: ~]# yum i nstal l net-snmp net-snmp-l i bs net-snmp-uti l s For more information on how to install new packages in Red Hat Enterprise Linux, see Section 7.2.4, “ Installing Packages” . 18.6.2. Running t he Net -SNMP Daemon The net-snmp package contains snmpd , the SNMP Agent D aemon. This section provides information on how to start, stop, and restart the snmpd service. For more information on managing system services in Red Hat Enterprise Linux 7, see Chapter 8, Managing Services with systemd. 1 8 .6 .2 .1 . St art ing t he Se rvice To run the snmpd service in the current session, type the following at a shell prompt as ro o t: 308 Chapt er 1 8 . Syst em Monit oring T ools systemctl start snmpd . servi ce To configure the service to be automatically started at boot time, use the following command: systemctl enabl e snmpd . servi ce 1 8 .6 .2 .2 . St o pping t he Se rvice To stop the running snmpd service, type the following at a shell prompt as ro o t: systemctl sto p snmpd . servi ce To disable starting the service at boot time, use the following command: systemctl d i sabl e snmpd . servi ce 1 8 .6 .2 .3. Re st art ing t he Se rvice To restart the running snmpd service, type the following at a shell prompt: systemctl restart snmpd . servi ce This command stops the service and starts it again in quick succession. To only reload the configuration without stopping the service, run the following command instead: systemctl rel o ad snmpd . servi ce This causes the running snmpd service to reload its configuration. 18.6.3. Configuring Net -SNMP To change the Net-SNMP Agent D aemon configuration, edit the /etc/snmp/snmpd . co nf configuration file. The default snmpd . co nf file included with Red Hat Enterprise Linux 7 is heavily commented and serves as a good starting point for agent configuration. This section focuses on two common tasks: setting system information and configuring authentication. For more information about available configuration directives, see the snmpd . co nf(5) manual page. Additionally, there is a utility in the net-snmp package named snmpco nf which can be used to interactively generate a valid agent configuration. Note that the net-snmp-utils package must be installed in order to use the snmpwal k utility described in this section. Note For any changes to the configuration file to take effect, force the snmpd service to re-read the configuration by running the following command as ro o t: systemctl rel o ad snmpd . servi ce 309 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 1 8 .6 .3.1 . Se t t ing Syst e m Info rm at io n Net-SNMP provides some rudimentary system information via the system tree. For example, the following snmpwal k command shows the system tree with a default agent configuration. ~]# snmpwal k -v2c -c publ i c l o cal ho st system SNMPv2-MIB::sysDescr.0 = STRING: Linux localhost.localdomain 3.10.0123.el7.x86_64 #1 SMP Mon May 5 11:16:57 EDT 2014 x86_64 SNMPv2-MIB::sysObjectID.0 = OID: NET-SNMP-MIB::netSnmpAgentOIDs.10 DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (464) 0:00:04.64 SNMPv2-MIB::sysContact.0 = STRING: Root (configure /etc/snmp/snmp.local.conf) [output truncated] By default, the sysName object is set to the host name. The sysLo cati o n and sysC o ntact objects can be configured in the /etc/snmp/snmpd . co nf file by changing the value of the sysl o cati o n and sysco ntact directives, for example: syslocation Datacenter, Row 4, Rack 3 syscontact UNIX Admin After making changes to the configuration file, reload the configuration and test it by running the snmpwal k command again: ~]# systemctl rel o ad snmp. servi ce ~]# snmpwal k -v2c -c publ i c l o cal ho st system SNMPv2-MIB::sysDescr.0 = STRING: Linux localhost.localdomain 3.10.0123.el7.x86_64 #1 SMP Mon May 5 11:16:57 EDT 2014 x86_64 SNMPv2-MIB::sysObjectID.0 = OID: NET-SNMP-MIB::netSnmpAgentOIDs.10 DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (35424) 0:05:54.24 SNMPv2-MIB::sysContact.0 = STRING: UNIX Ad mi n SNMPv2-MIB::sysName.0 = STRING: localhost.localdomain SNMPv2-MIB::sysLocation.0 = STRING: D atacenter, R o w 4 , R ack 3 [output truncated] 1 8 .6 .3.2 . Co nfiguring Aut he nt icat io n The Net-SNMP Agent D aemon supports all three versions of the SNMP protocol. The first two versions (1 and 2c) provide for simple authentication using a community string. This string is a shared secret between the agent and any client utilities. The string is passed in clear text over the network however and is not considered secure. Version 3 of the SNMP protocol supports user authentication and message encryption using a variety of protocols. The Net-SNMP agent also supports tunneling over SSH, TLS authentication with X.509 certificates, and Kerberos authentication. C o n f ig u rin g SN MP Versio n 2c C o mmu n it y To configure an SN MP versio n 2c co mmu n it y, use either the ro co mmuni ty or rwco mmuni ty directive in the /etc/snmp/snmpd . co nf configuration file. The format of the directives is as follows: directive community [source [OID]] … where community is the community string to use, source is an IP address or subnet, and OID is the SNMP tree to provide access to. For example, the following directive provides read-only access to the system tree to a client using the community string “ redhat” on the local machine: 310 Chapt er 1 8 . Syst em Monit oring T ools rocommunity redhat 127.0.0.1 .1.3.6.1.2.1.1 To test the configuration, use the snmpwal k command with the -v and -c options. ~]# snmpwal k -v2c -c red hat l o cal ho st system SNMPv2-MIB::sysDescr.0 = STRING: Linux localhost.localdomain 3.10.0123.el7.x86_64 #1 SMP Mon May 5 11:16:57 EDT 2014 x86_64 SNMPv2-MIB::sysObjectID.0 = OID: NET-SNMP-MIB::netSnmpAgentOIDs.10 DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (101376) 0:16:53.76 SNMPv2-MIB::sysContact.0 = STRING: UNIX Admin SNMPv2-MIB::sysName.0 = STRING: localhost.localdomain SNMPv2-MIB::sysLocation.0 = STRING: Datacenter, Row 4, Rack 3 [output truncated] C o n f ig u rin g SN MP Versio n 3 U ser To configure an SN MP versio n 3 u ser, use the net-snmp-create-v3-user command. This command adds entries to the /var/l i b/net-snmp/snmpd . co nf and /etc/snmp/snmpd . co nf files which create the user and grant access to the user. Note that the net-snmp-create-v3-user command may only be run when the agent is not running. The following example creates the “ admin” user with the password “ redhatsnmp” : ~]# systemctl sto p snmpd . servi ce ~]# net-snmp-create-v3-user Enter a SNMPv3 user name to create: admin Enter authentication pass-phrase: redhatsnmp Enter encryption pass-phrase: [press return to reuse the authentication pass-phrase] adding the following line to /var/lib/net-snmp/snmpd.conf: createUser admin MD5 "redhatsnmp" DES adding the following line to /etc/snmp/snmpd.conf: rwuser admin ~]# systemctl start snmpd . servi ce The rwuser directive (or ro user when the -ro command line option is supplied) that net-snmpcreate-v3-user adds to /etc/snmp/snmpd . co nf has a similar format to the rwco mmuni ty and ro co mmuni ty directives: directive user [no auth|auth|pri v] [OID] … where user is a user name and OID is the SNMP tree to provide access to. By default, the NetSNMP Agent D aemon allows only authenticated requests (the auth option). The no auth option allows you to permit unauthenticated requests, and the pri v option enforces the use of encryption. The authpri v option specifies that requests must be authenticated and replies should be encrypted. For example, the following line grants the user “ admin” read-write access to the entire tree: rwuser admin authpriv .1 To test the configuration, create a . snmp directory in your user's home directory and a configuration file named snmp. co nf in that directory (~ /. snmp/snmp. co nf) with the following lines: 311 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide defVersion 3 defSecurityLevel authPriv defSecurityName admin defPassphrase redhatsnmp The snmpwal k command will now use these authentication settings when querying the agent: ~]$ snmpwal k -v3 l o cal ho st system SNMPv2-MIB::sysDescr.0 = STRING: Linux localhost.localdomain 3.10.0123.el7.x86_64 #1 SMP Mon May 5 11:16:57 EDT 2014 x86_64 [output truncated] 18.6.4 . Ret rieving Performance Dat a over SNMP The Net-SNMP Agent in Red Hat Enterprise Linux provides a wide variety of performance information over the SNMP protocol. In addition, the agent can be queried for a listing of the installed RPM packages on the system, a listing of currently running processes on the system, or the network configuration of the system. This section provides an overview of OID s related to performance tuning available over SNMP. It assumes that the net-snmp-utils package is installed and that the user is granted access to the SNMP tree as described in Section 18.6.3.2, “ Configuring Authentication” . 1 8 .6 .4 .1 . Hardware Co nfigurat io n The Ho st R eso urces MIB included with Net-SNMP presents information about the current hardware and software configuration of a host to a client utility. Table 18.3, “ Available OID s” summarizes the different OID s available under that MIB. T ab le 18.3. Availab le O ID s O ID D escrip t io n HO ST -R ESO UR C ES-MIB: : hrSystem Contains general system information such as uptime, number of users, and number of running processes. Contains data on memory and file system usage. Contains a listing of all processors, network devices, and file systems. Contains a listing of all running processes. Contains memory and CPU statistics on the process table from HOST-RESOURCESMIB::hrSWRun. Contains a listing of the RPM database. HO ST -R ESO UR C ES-MIB: : hrSto rag e HO ST -R ESO UR C ES-MIB: : hrD evi ces HO ST -R ESO UR C ES-MIB: : hrSWR un HO ST -R ESO UR C ES-MIB: : hrSWR unP erf HO ST -R ESO UR C ES-MIB: : hrSWInstal l ed There are also a number of SNMP tables available in the Host Resources MIB which can be used to retrieve a summary of the available information. The following example displays HO ST R ESO UR C ES-MIB: : hrFST abl e: ~]$ snmptabl e -C b l o cal ho st HO ST -R ESO UR C ES-MIB: : hrFST abl e SNMP table: HOST-RESOURCES-MIB::hrFSTable Index MountPoint RemoteMountPoint 312 Type Chapt er 1 8 . Syst em Monit oring T ools Access Bootable StorageIndex LastFullBackupDate LastPartialBackupDate 1 "/" "" HOST-RESOURCES-TYPES::hrFSLinuxExt2 readWrite true 31 0-1-1,0:0:0.0 0-1-1,0:0:0.0 5 "/dev/shm" "" HOST-RESOURCES-TYPES::hrFSOther readWrite false 35 0-1-1,0:0:0.0 0-1-1,0:0:0.0 6 "/boot" "" HOST-RESOURCES-TYPES::hrFSLinuxExt2 readWrite false 36 0-1-1,0:0:0.0 0-1-1,0:0:0.0 For more information about HO ST -R ESO UR C ES-MIB, see the /usr/share/snmp/mi bs/HO ST R ESO UR C ES-MIB. txt file. 1 8 .6 .4 .2 . CPU and Me m o ry Info rm at io n Most system performance data is available in the UC D SNMP MIB. The systemStats OID provides a number of counters around processor usage: ~]$ snmpwal k l o cal ho st UC D -SNMP -MIB: : systemStats UCD-SNMP-MIB::ssIndex.0 = INTEGER: 1 UCD-SNMP-MIB::ssErrorName.0 = STRING: systemStats UCD-SNMP-MIB::ssSwapIn.0 = INTEGER: 0 kB UCD-SNMP-MIB::ssSwapOut.0 = INTEGER: 0 kB UCD-SNMP-MIB::ssIOSent.0 = INTEGER: 0 blocks/s UCD-SNMP-MIB::ssIOReceive.0 = INTEGER: 0 blocks/s UCD-SNMP-MIB::ssSysInterrupts.0 = INTEGER: 29 interrupts/s UCD-SNMP-MIB::ssSysContext.0 = INTEGER: 18 switches/s UCD-SNMP-MIB::ssCpuUser.0 = INTEGER: 0 UCD-SNMP-MIB::ssCpuSystem.0 = INTEGER: 0 UCD-SNMP-MIB::ssCpuIdle.0 = INTEGER: 99 UCD-SNMP-MIB::ssCpuRawUser.0 = Counter32: 2278 UCD-SNMP-MIB::ssCpuRawNice.0 = Counter32: 1395 UCD-SNMP-MIB::ssCpuRawSystem.0 = Counter32: 6826 UCD-SNMP-MIB::ssCpuRawIdle.0 = Counter32: 3383736 UCD-SNMP-MIB::ssCpuRawWait.0 = Counter32: 7629 UCD-SNMP-MIB::ssCpuRawKernel.0 = Counter32: 0 UCD-SNMP-MIB::ssCpuRawInterrupt.0 = Counter32: 434 UCD-SNMP-MIB::ssIORawSent.0 = Counter32: 266770 UCD-SNMP-MIB::ssIORawReceived.0 = Counter32: 427302 UCD-SNMP-MIB::ssRawInterrupts.0 = Counter32: 743442 UCD-SNMP-MIB::ssRawContexts.0 = Counter32: 718557 UCD-SNMP-MIB::ssCpuRawSoftIRQ.0 = Counter32: 128 UCD-SNMP-MIB::ssRawSwapIn.0 = Counter32: 0 UCD-SNMP-MIB::ssRawSwapOut.0 = Counter32: 0 In particular, the ssC puR awUser, ssC puR awSystem, ssC puR awWai t, and ssC puR awId l e OID s provide counters which are helpful when determining whether a system is spending most of its processor time in kernel space, user space, or I/O. ssR awSwapIn and ssR awSwapO ut can be helpful when determining whether a system is suffering from memory exhaustion. More memory information is available under the UC D -SNMP -MIB: : memo ry OID , which provides similar data to the free command: ~]$ snmpwal k l o cal ho st UC D -SNMP -MIB: : memo ry UCD-SNMP-MIB::memIndex.0 = INTEGER: 0 UCD-SNMP-MIB::memErrorName.0 = STRING: swap UCD-SNMP-MIB::memTotalSwap.0 = INTEGER: 1023992 kB 313 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide UCD-SNMP-MIB::memAvailSwap.0 = INTEGER: 1023992 kB UCD-SNMP-MIB::memTotalReal.0 = INTEGER: 1021588 kB UCD-SNMP-MIB::memAvailReal.0 = INTEGER: 634260 kB UCD-SNMP-MIB::memTotalFree.0 = INTEGER: 1658252 kB UCD-SNMP-MIB::memMinimumSwap.0 = INTEGER: 16000 kB UCD-SNMP-MIB::memBuffer.0 = INTEGER: 30760 kB UCD-SNMP-MIB::memCached.0 = INTEGER: 216200 kB UCD-SNMP-MIB::memSwapError.0 = INTEGER: noError(0) UCD-SNMP-MIB::memSwapErrorMsg.0 = STRING: Load averages are also available in the UC D SNMP MIB. The SNMP table UC D -SNMP MIB: : l aT abl e has a listing of the 1, 5, and 15 minute load averages: ~]$ snmptabl e l o cal ho st UC D -SNMP -MIB: : l aT abl e SNMP table: UCD-SNMP-MIB::laTable laIndex laNames laLoad laConfig laLoadInt laLoadFloat laErrorFlag laErrMessage 1 Load-1 0.00 12.00 0 0.000000 noError 2 Load-5 0.00 12.00 0 0.000000 noError 3 Load-15 0.00 12.00 0 0.000000 noError 1 8 .6 .4 .3. File Syst e m and Disk Info rm at io n The Ho st R eso urces MIB provides information on file system size and usage. Each file system (and also each memory pool) has an entry in the HO ST -R ESO UR C ES-MIB: : hrSto rag eT abl e table: ~]$ snmptabl e -C b l o cal ho st HO ST -R ESO UR C ES-MIB: : hrSto rag eT abl e SNMP table: HOST-RESOURCES-MIB::hrStorageTable Index Type Descr AllocationUnits Size Used AllocationFailures 1 HOST-RESOURCES-TYPES::hrStorageRam Physical memory 1024 Bytes 1021588 388064 ? 3 HOST-RESOURCES-TYPES::hrStorageVirtualMemory Virtual memory 1024 Bytes 2045580 388064 ? 6 HOST-RESOURCES-TYPES::hrStorageOther Memory buffers 1024 Bytes 1021588 31048 ? 7 HOST-RESOURCES-TYPES::hrStorageOther Cached memory 1024 Bytes 216604 216604 ? 10 HOST-RESOURCES-TYPES::hrStorageVirtualMemory Swap space 1024 Bytes 1023992 0 ? 31 HOST-RESOURCES-TYPES::hrStorageFixedDisk / 4096 Bytes 2277614 250391 ? 35 HOST-RESOURCES-TYPES::hrStorageFixedDisk /dev/shm 4096 Bytes 127698 0 ? 36 HOST-RESOURCES-TYPES::hrStorageFixedDisk /boot 1024 Bytes 198337 26694 ? The OID s under HO ST -R ESO UR C ES-MIB: : hrSto rag eSi ze and HO ST -R ESO UR C ESMIB: : hrSto rag eUsed can be used to calculate the remaining capacity of each mounted file system. I/O data is available both in UC D -SNMP -MIB: : systemStats (ssIO R awSent. 0 and 314 Chapt er 1 8 . Syst em Monit oring T ools ssIO R awR eci eved . 0 ) and in UC D -D ISKIO -MIB: : d i skIO T abl e. The latter provides much more granular data. Under this table are OID s for d i skIO NR ead X and d i skIO NWri ttenX, which provide counters for the number of bytes read from and written to the block device in question since the system boot: ~]$ snmptabl e -C b l o cal ho st UC D -D ISKIO -MIB: : d i skIO T abl e SNMP table: UCD-DISKIO-MIB::diskIOTable Index Device NRead NWritten Reads Writes LA1 LA5 LA15 NReadX NWrittenX ... 25 sda 216886272 139109376 16409 4894 ? ? ? 216886272 139109376 26 sda1 2455552 5120 613 2 ? ? ? 2455552 5120 27 sda2 1486848 0 332 0 ? ? ? 1486848 0 28 sda3 212321280 139104256 15312 4871 ? ? ? 212321280 139104256 1 8 .6 .4 .4 . Ne t wo rk Info rm at io n The Interfaces MIB provides information on network devices. IF-MIB: : i fT abl e provides an SNMP table with an entry for each interface on the system, the configuration of the interface, and various packet counters for the interface. The following example shows the first few columns of i fT abl e on a system with two physical network interfaces: ~]$ snmptabl e -C b l o cal ho st IF-MIB: : i fT abl e SNMP table: IF-MIB::ifTable Index Descr Type Mtu Speed PhysAddress AdminStatus 1 lo softwareLoopback 16436 10000000 up 2 eth0 ethernetCsmacd 1500 0 52:54:0:c7:69:58 up 3 eth1 ethernetCsmacd 1500 0 52:54:0:a7:a3:24 down Network traffic is available under the OID s IF-MIB: : i fO utO ctets and IF-MIB: : i fInO ctets. The following SNMP queries will retrieve network traffic for each of the interfaces on this system: ~]$ snmpwal k l o cal ho st IF-MIB: : i fD escr IF-MIB::ifDescr.1 = STRING: lo IF-MIB::ifDescr.2 = STRING: eth0 IF-MIB::ifDescr.3 = STRING: eth1 ~]$ snmpwal k l o cal ho st IF-MIB: : i fO utO ctets IF-MIB::ifOutOctets.1 = Counter32: 10060699 IF-MIB::ifOutOctets.2 = Counter32: 650 IF-MIB::ifOutOctets.3 = Counter32: 0 ~]$ snmpwal k l o cal ho st IF-MIB: : i fInO ctets IF-MIB::ifInOctets.1 = Counter32: 10060699 IF-MIB::ifInOctets.2 = Counter32: 78650 IF-MIB::ifInOctets.3 = Counter32: 0 18.6.5. Ext ending Net -SNMP 315 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The Net-SNMP Agent can be extended to provide application metrics in addition to raw system metrics. This allows for capacity planning as well as performance issue troubleshooting. For example, it may be helpful to know that an email system had a 5-minute load average of 15 while being tested, but it is more helpful to know that the email system has a load average of 15 while processing 80,000 messages a second. When application metrics are available via the same interface as the system metrics, this also allows for the visualization of the impact of different load scenarios on system performance (for example, each additional 10,000 messages increases the load average linearly until 100,000). A number of the applications included in Red Hat Enterprise Linux extend the Net-SNMP Agent to provide application metrics over SNMP. There are several ways to extend the agent for custom applications as well. This section describes extending the agent with shell scripts and the Perl plugins from the Optional channel. It assumes that the net-snmp-utils and net-snmp-perl packages are installed, and that the user is granted access to the SNMP tree as described in Section 18.6.3.2, “ Configuring Authentication” . 1 8 .6 .5 .1 . Ext e nding Ne t -SNMP wit h She ll Script s The Net-SNMP Agent provides an extension MIB (NET -SNMP -EXT END -MIB) that can be used to query arbitrary shell scripts. To specify the shell script to run, use the extend directive in the /etc/snmp/snmpd . co nf file. Once defined, the Agent will provide the exit code and any output of the command over SNMP. The example below demonstrates this mechanism with a script which determines the number of httpd processes in the process table. Note The Net-SNMP Agent also provides a built-in mechanism for checking the process table via the pro c directive. See the sn mp d .co n f (5) manual page for more information. The exit code of the following shell script is the number of httpd processes running on the system at a given point in time: # !/bin/sh N UMPIDS=`pgrep httpd | wc -l` e xit $NUMPIDS To make this script available over SNMP, copy the script to a location on the system path, set the executable bit, and add an extend directive to the /etc/snmp/snmpd . co nf file. The format of the extend directive is the following: extend name prog args … where name is an identifying string for the extension, prog is the program to run, and args are the arguments to give the program. For instance, if the above shell script is copied to /usr/l o cal /bi n/check_apache. sh, the following directive will add the script to the SNMP tree: extend httpd_pids /bin/sh /usr/local/bin/check_apache.sh The script can then be queried at NET -SNMP -EXT END -MIB: : nsExtend O bjects: ~]$ snmpwal k l o cal ho st NET -SNMP -EXT END -MIB: : nsExtend O bjects 316 Chapt er 1 8 . Syst em Monit oring T ools NET-SNMP-EXTEND-MIB::nsExtendNumEntries.0 = INTEGER: 1 NET-SNMP-EXTEND-MIB::nsExtendCommand."httpd_pids" = STRING: /bin/sh NET-SNMP-EXTEND-MIB::nsExtendArgs."httpd_pids" = STRING: /usr/local/bin/check_apache.sh NET-SNMP-EXTEND-MIB::nsExtendInput."httpd_pids" = STRING: NET-SNMP-EXTEND-MIB::nsExtendCacheTime."httpd_pids" = INTEGER: 5 NET-SNMP-EXTEND-MIB::nsExtendExecType."httpd_pids" = INTEGER: exec(1) NET-SNMP-EXTEND-MIB::nsExtendRunType."httpd_pids" = INTEGER: run-onread(1) NET-SNMP-EXTEND-MIB::nsExtendStorage."httpd_pids" = INTEGER: permanent(4) NET-SNMP-EXTEND-MIB::nsExtendStatus."httpd_pids" = INTEGER: active(1) NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."httpd_pids" = STRING: NET-SNMP-EXTEND-MIB::nsExtendOutputFull."httpd_pids" = STRING: NET-SNMP-EXTEND-MIB::nsExtendOutNumLines."httpd_pids" = INTEGER: 1 NET-SNMP-EXTEND-MIB::nsExtendResult."httpd_pids" = INTEGER: 8 NET-SNMP-EXTEND-MIB::nsExtendOutLine."httpd_pids".1 = STRING: Note that the exit code (“ 8” in this example) is provided as an INTEGER type and any output is provided as a STRING type. To expose multiple metrics as integers, supply different arguments to the script using the extend directive. For example, the following shell script can be used to determine the number of processes matching an arbitrary string, and will also output a text string giving the number of processes: # !/bin/sh P ATTERN=$1 N UMPIDS=`pgrep $PATTERN | wc -l` e cho "There are $NUMPIDS $PATTERN processes." e xit $NUMPIDS The following /etc/snmp/snmpd . co nf directives will give both the number of httpd PID s as well as the number of snmpd PID s when the above script is copied to /usr/l o cal /bi n/check_pro c. sh: extend httpd_pids /bin/sh /usr/local/bin/check_proc.sh httpd extend snmpd_pids /bin/sh /usr/local/bin/check_proc.sh snmpd The following example shows the output of an snmpwal k of the nsExtend O bjects OID : ~]$ snmpwal k l o cal ho st NET -SNMP -EXT END -MIB: : nsExtend O bjects NET-SNMP-EXTEND-MIB::nsExtendNumEntries.0 = INTEGER: 2 NET-SNMP-EXTEND-MIB::nsExtendCommand."httpd_pids" = STRING: /bin/sh NET-SNMP-EXTEND-MIB::nsExtendCommand."snmpd_pids" = STRING: /bin/sh NET-SNMP-EXTEND-MIB::nsExtendArgs."httpd_pids" = STRING: /usr/local/bin/check_proc.sh httpd NET-SNMP-EXTEND-MIB::nsExtendArgs."snmpd_pids" = STRING: /usr/local/bin/check_proc.sh snmpd NET-SNMP-EXTEND-MIB::nsExtendInput."httpd_pids" = STRING: NET-SNMP-EXTEND-MIB::nsExtendInput."snmpd_pids" = STRING: ... NET-SNMP-EXTEND-MIB::nsExtendResult."httpd_pids" = INTEGER: 8 NET-SNMP-EXTEND-MIB::nsExtendResult."snmpd_pids" = INTEGER: 1 317 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide NET-SNMP-EXTEND-MIB::nsExtendOutLine."httpd_pids".1 = STRING: There are 8 httpd processes. NET-SNMP-EXTEND-MIB::nsExtendOutLine."snmpd_pids".1 = STRING: There are 1 snmpd processes. Integer exit codes are limited Integer exit codes are limited to a range of 0–255. For values that are likely to exceed 256, either use the standard output of the script (which will be typed as a string) or a different method of extending the agent. This last example shows a query for the free memory of the system and the number of httpd processes. This query could be used during a performance test to determine the impact of the number of processes on memory pressure: ~]$ snmpg et l o cal ho st \ ' NET -SNMP -EXT END -MIB: : nsExtend R esul t. "httpd _pi d s"' \ UC D -SNMP -MIB: : memAvai l R eal . 0 NET-SNMP-EXTEND-MIB::nsExtendResult."httpd_pids" = INTEGER: 8 UCD-SNMP-MIB::memAvailReal.0 = INTEGER: 799664 kB 1 8 .6 .5 .2 . Ext e nding Ne t -SNMP wit h Pe rl Executing shell scripts using the extend directive is a fairly limited method for exposing custom application metrics over SNMP. The Net-SNMP Agent also provides an embedded Perl interface for exposing custom objects. The net-snmp-perl package in the Optional channel provides the NetSNMP : : ag ent Perl module that is used to write embedded Perl plug-ins on Red Hat Enterprise Linux. Note Before subscribing to the Optional and Supplementary channels see the Scope of Coverage D etails. If you decide to install packages from these channels, follow the steps documented in the article called How to access Optional and Supplementary channels, and -devel packages using Red Hat Subscription Manager (RHSM)? on the Red Hat Customer Portal. The NetSNMP : : ag ent Perl module provides an ag ent object which is used to handle requests for a part of the agent's OID tree. The ag ent object's constructor has options for running the agent as a sub-agent of snmpd or a standalone agent. No arguments are necessary to create an embedded agent: u se NetSNMP::agent (':all'); m y $agent = new NetSNMP::agent(); The ag ent object has a reg i ster method which is used to register a callback function with a particular OID . The reg i ster function takes a name, OID , and pointer to the callback function. The following example will register a callback function named hel l o _hand l er with the SNMP Agent which will handle requests under the OID . 1. 3. 6 . 1. 4 . 1. 80 72. 9 9 9 9 . 9 9 9 9 : 318 Chapt er 1 8 . Syst em Monit oring T ools $ agent->register("hello_world", ".1.3.6.1.4.1.8072.9999.9999", \& hello_handler); Note The OID . 1. 3. 6 . 1. 4 . 1. 80 72. 9 9 9 9 . 9 9 9 9 (NET -SNMP -MIB: : netSnmpP l aypen) is typically used for demonstration purposes only. If your organization does not already have a root OID , you can obtain one by contacting an ISO Name Registration Authority (ANSI in the United States). The handler function will be called with four parameters, HANDLER, REGISTRATION_INFO, REQUEST_INFO, and REQUESTS. The REQUESTS parameter contains a list of requests in the current call and should be iterated over and populated with data. The req uest objects in the list have get and set methods which allow for manipulating the OID and value of the request. For example, the following call will set the value of a request object to the string “ hello world” : $ request->setValue(ASN_OCTET_STR, "hello world"); The handler function should respond to two types of SNMP requests: the GET request and the GETNEXT request. The type of request is determined by calling the g etMo d e method on the req uest_i nfo object passed as the third parameter to the handler function. If the request is a GET request, the caller will expect the handler to set the value of the req uest object, depending on the OID of the request. If the request is a GETNEXT request, the caller will also expect the handler to set the OID of the request to the next available OID in the tree. This is illustrated in the following code example: m y $request; m y $string_value = "hello world"; m y $integer_value = "8675309"; for($request = $requests; $request; $request = $request->next()) { my $oid = $request->getOID(); if ($request_info->getMode() == MODE_GET) { if ($oid == new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.0")) { $request->setValue(ASN_OCTET_STR, $string_value); } elsif ($oid == new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.1")) { $request->setValue(ASN_INTEGER, $integer_value); } } elsif ($request_info->getMode() == MODE_GETNEXT) { if ($oid == new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.0")) { $request->setOID(".1.3.6.1.4.1.8072.9999.9999.1.1"); $request->setValue(ASN_INTEGER, $integer_value); } elsif ($oid < new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.0")) { $request->setOID(".1.3.6.1.4.1.8072.9999.9999.1.0"); $request->setValue(ASN_OCTET_STR, $string_value); } } } When g etMo d e returns MO D E_G ET , the handler analyzes the value of the g etO ID call on the 319 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide req uest object. The value of the req uest is set to either stri ng _val ue if the OID ends in “ .1.0” , or set to i nteg er_val ue if the OID ends in “ .1.1” . If the g etMo d e returns MO D E_G ET NEXT , the handler determines whether the OID of the request is “ .1.0” , and then sets the OID and value for “ .1.1” . If the request is higher on the tree than “ .1.0” , the OID and value for “ .1.0” is set. This in effect returns the “ next” value in the tree so that a program like snmpwal k can traverse the tree without prior knowledge of the structure. The type of the variable is set using constants from NetSNMP : : ASN. See the perl d o c for NetSNMP : : ASN for a full list of available constants. The entire code listing for this example Perl plug-in is as follows: # !/usr/bin/perl u se NetSNMP::agent (':all'); u se NetSNMP::ASN qw(ASN_OCTET_STR ASN_INTEGER); sub hello_handler { my ($handler, $registration_info, $request_info, $requests) = @ _; my $request; my $string_value = "hello world"; my $integer_value = "8675309"; for($request = $requests; $request; $request = $request->next()) { my $oid = $request->getOID(); if ($request_info->getMode() == MODE_GET) { if ($oid == new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.0")) { $request->setValue(ASN_OCTET_STR, $string_value); } elsif ($oid == new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.1")) { $request->setValue(ASN_INTEGER, $integer_value); } } elsif ($request_info->getMode() == MODE_GETNEXT) { if ($oid == new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.0")) { $request->setOID(".1.3.6.1.4.1.8072.9999.9999.1.1"); $request->setValue(ASN_INTEGER, $integer_value); } elsif ($oid < new NetSNMP::OID(".1.3.6.1.4.1.8072.9999.9999.1.0")) { $request->setOID(".1.3.6.1.4.1.8072.9999.9999.1.0"); $request->setValue(ASN_OCTET_STR, $string_value); } } } } m y $agent = new NetSNMP::agent(); $ agent->register("hello_world", ".1.3.6.1.4.1.8072.9999.9999", \& hello_handler); To test the plug-in, copy the above program to /usr/share/snmp/hel l o _wo rl d . pl and add the following line to the /etc/snmp/snmpd . co nf configuration file: perl do "/usr/share/snmp/hello_world.pl" 320 Chapt er 1 8 . Syst em Monit oring T ools The SNMP Agent D aemon will need to be restarted to load the new Perl plug-in. Once it has been restarted, an snmpwal k should return the new data: ~]$ snmpwal k l o cal ho st NET -SNMP -MIB: : netSnmpP l aypen NET-SNMP-MIB::netSnmpPlaypen.1.0 = STRING: "hello world" NET-SNMP-MIB::netSnmpPlaypen.1.1 = INTEGER: 8675309 The snmpg et should also be used to exercise the other mode of the handler: ~]$ snmpg et l o cal ho st \ NET -SNMP -MIB: : netSnmpP l aypen. 1. 0 \ NET -SNMP -MIB: : netSnmpP l aypen. 1. 1 NET-SNMP-MIB::netSnmpPlaypen.1.0 = STRING: "hello world" NET-SNMP-MIB::netSnmpPlaypen.1.1 = INTEGER: 8675309 18.7. Addit ional Resources To learn more about gathering system information, see the following resources. 18.7.1. Inst alled Document at ion lscp u (1) — The manual page for the l scpu command. lsu sb (8) — The manual page for the l susb command. f in d mn t (8) — The manual page for the fi nd mnt command. b lkid (8) — The manual page for the bl ki d command. lsb lk(8) — The manual page for the l sbl k command. p s(1) — The manual page for the ps command. t o p (1) — The manual page for the to p command. f ree(1) — The manual page for the free command. d f (1) — The manual page for the d f command. d u (1) — The manual page for the d u command. lsp ci(8) — The manual page for the l spci command. sn mp d (8) — The manual page for the snmpd service. sn mp d .co n f (5) — The manual page for the /etc/snmp/snmpd . co nf file containing full documentation of available configuration directives. 321 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 19. OpenLMI The O p en Lin u x Man ag emen t In f rast ru ct u re, commonly abbreviated as O p en LMI, is a common infrastructure for the management of Linux systems. It builds on top of existing tools and serves as an abstraction layer in order to hide much of the complexity of the underlying system from system administrators. OpenLMI is distributed with a set of services that can be accessed locally or remotely and provides multiple language bindings, standard APIs, and standard scripting interfaces that can be used to manage and monitor hardware, operating systems, and system services. 19.1. About OpenLMI OpenLMI is designed to provide a common management interface to production servers running the Red Hat Enterprise Linux system on both physical and virtual machines. It consists of the following three components: 1. System management agents — these agents are installed on a managed system and implement an object model that is presented to a standard object broker. The initial agents implemented in OpenLMI include storage configuration and network configuration, but later work will address additional elements of system management. The system management agents are commonly referred to as Common Information Model providers or CIM providers. 2. A standard object broker — the object broker manages system management agents and provides an interface to them. The standard object broker is also known as a CIM Object Monitor or CIMOM. 3. Client applications and scripts — the client applications and scripts call the system management agents through the standard object broker. The OpenLMI project complements existing management initiatives by providing a low-level interface that can be used by scripts or system management consoles. Interfaces distributed with OpenLMI include C, C++, Python, Java, and an interactive command line client, and all of them offer the same full access to the capabilities implemented in each agent. This ensures that you always have access to exactly the same capabilities no matter which programming interface you decide to use. 19.1.1. Main Feat ures The following are key benefits of installing and using OpenLMI on your system: OpenLMI provides a standard interface for configuration, management, and monitoring of your local and remote systems. It allows you to configure, manage, and monitor production servers running on both physical and virtual machines. It is distributed with a collection of CIM providers that allow you to configure, manage, and monitor storage devices and complex networks. It allows you to call system management functions from C, C++, Python, and Java programs, and includes LMIShell, which provides a command line interface. It is free software based on open industry standards. 19.1.2. Management Capabilit ies Key capabilities of OpenLMI include the management of storage devices, networks, system services, user accounts, hardware and software configuration, power management, and interaction with Active 322 Chapt er 1 9 . O penLMI D irectory. For a complete list of CIM providers that are distributed with Red Hat Enterprise Linux 7, see Table 19.1, “ Available CIM Providers” . T ab le 19 .1. Availab le C IM Pro vid ers Packag e N ame D escrip t io n openlmi-account openlmi-logicalfile openlmi-networking openlmi-powermanagement openlmi-service openlmi-storage openlmi-fan openlmi-hardware openlmi-realmd A CIM provider A CIM provider A CIM provider A CIM provider A CIM provider A CIM provider A CIM provider A CIM provider A CIM provider A CIM provider openlmi-software [a] for for for for for for for for for for managing user accounts. reading files and directories. network management. power management. managing system services. storage management. controlling computer fans. retrieving hardware information. configuring realmd. software management. [a] In Red Hat Enterp ris e Linux 7, the O p enLMI So ftware p ro vid er is inc lud ed as a Tec hno lo g y Preview. This p ro vid er is fully func tio nal, b ut has a kno wn p erfo rmanc e s c aling is s ue where lis ting larg e numb ers o f s o ftware p ac kag es may c o ns ume exc es s ive amo unt o f memo ry and time. To wo rk aro und this is s ue, ad jus t p ac kag e s earc hes to return as few p ac kag es as p o s s ib le. 19.2. Inst alling OpenLMI OpenLMI is distributed as a collection of RPM packages that include the CIMOM, individual CIM providers, and client applications. This allows you distinguish between a managed and client system and install only those components you need. 19.2.1. Inst alling OpenLMI on a Managed Syst em A managed system is the system you intend to monitor and manage by using the OpenLMI client tools. To install OpenLMI on a managed system, complete the following steps: 1. Install the tog-pegasus package by typing the following at a shell prompt as ro o t: yum i nstal l to g -peg asus This command installs the OpenPegasus CIMOM and all its dependencies to the system and creates a user account for the peg asus user. 2. Install required CIM providers by running the following command as ro o t: yum i nstal l o penl mi {sto rag e,netwo rki ng ,servi ce,acco unt,po wermanag ement} This command installs the CIM providers for storage, network, service, account, and power management. For a complete list of CIM providers distributed with Red Hat Enterprise Linux 7, see Table 19.1, “ Available CIM Providers” . 3. Edit the /etc/P eg asus/access. co nf configuration file to customize the list of users that are allowed to connect to the OpenPegasus CIMOM. By default, only the peg asus user is allowed to access the CIMOM both remotely and locally. To activate this user account, run the following command as ro o t to set the user's password: 323 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide passwd peg asus 4. Start the OpenPegasus CIMOM by activating the to g -peg asus. servi ce unit. To activate the to g -peg asus. servi ce unit in the current session, type the following at a shell prompt as ro o t: systemctl start to g -peg asus. servi ce To configure the to g -peg asus. servi ce unit to start automatically at boot time, type as ro o t: systemctl enabl e to g -peg asus. servi ce 5. If you intend to interact with the managed system from a remote machine, enable TCP communication on port 59 89 (wbem-https). To open this port in the current session, run the following command as ro o t: fi rewal l -cmd --ad d -po rt 59 89 /tcp To open port 59 89 for TCP communication permanently, type as ro o t: fi rewal l -cmd --permanent --ad d -po rt 59 89 /tcp You can now connect to the managed system and interact with it by using the OpenLMI client tools as described in Section 19.4, “ Using LMIShell” . If you intend to perform OpenLMI operations directly on the managed system, also complete the steps described in Section 19.2.2, “ Installing OpenLMI on a Client System” . 19.2.2. Inst alling OpenLMI on a Client Syst em A client system is the system from which you intend to interact with the managed system. In a typical scenario, the client system and the managed system are installed on two separate machines, but you can also install the client tools on the managed system and interact with it directly. To install OpenLMI on a client system, complete the following steps: 1. Install the openlmi-tools package by typing the following at a shell prompt as ro o t: yum i nstal l o penl mi -to o l s This command installs LMIShell, an interactive client and interpreter for accessing CIM objects provided by OpenPegasus, and all its dependencies to the system. 2. Configure SSL certificates for OpenPegasus as described in Section 19.3, “ Configuring SSL Certificates for OpenPegasus” . You can now use the LMIShell client to interact with the managed system as described in Section 19.4, “ Using LMIShell” . 19.3. Configuring SSL Cert ificat es for OpenPegasus 324 Chapt er 1 9 . O penLMI OpenLMI uses the Web-Based Enterprise Management (WBEM) protocol that functions over an HTTP transport layer. Standard HTTP Basic authentication is performed in this protocol, which means that the user name and password are transmitted alongside the requests. Configuring the OpenPegasus CIMOM to use HTTPS for communication is necessary to ensure secure authentication. A Secure Sockets Layer (SSL) or Transport Layer Security (TLS) certificate is required on the managed system to establish an encrypted channel. There are two ways of managing SSL/TLS certificates on a system: Self-signed certificates require less infrastructure to use, but are more difficult to deploy to clients and manage securely. Authority-signed certificates are easier to deploy to clients once they are set up, but may require a greater initial investment. When using an authority-signed certificate, it is necessary to configure a trusted certificate authority on the client systems. The authority can then be used for signing all of the managed systems' CIMOM certificates. Certificates can also be part of a certificate chain, so the certificate used for signing the managed systems' certificates may in turn be signed by another, higher authority (such as Verisign, CAcert, RSA and many others). The default certificate and trust store locations on the file system are listed in Table 19.2, “ Certificate and Trust Store Locations” . T ab le 19 .2. C ert if icat e an d T ru st St o re Lo cat io n s C o n f ig u rat io n O p t io n Lo cat io n D escrip t io n ssl C erti fi cateFi l eP a th ssl KeyFi l eP ath /etc/P eg asus/server. p em /etc/P eg asus/fi l e. pe m /etc/P eg asus/cl i ent. pem Public certificate of the CIMOM. ssl T rustSto re Private key known only to the CIMOM. The file or directory providing the list of trusted certificate authorities. Important If you modify any of the files mentioned in Table 19.2, “ Certificate and Trust Store Locations” , restart the to g -peg asus service to make sure it recognizes the new certificates. To restart the service, type the following at a shell prompt as ro o t: systemctl restart to g -peg asus. servi ce For more information on how to manage system services in Red Hat Enterprise Linux 7, see Chapter 8, Managing Services with systemd. 19.3.1. Managing Self-signed Cert ificat es A self-signed certificate uses its own private key to sign itself and it is not connected to any chain of trust. On a managed system, if certificates have not been provided by the administrator prior to the first time that the to g -peg asus service is started, a set of self-signed certificates will be automatically generated using the system's primary hostname as the certificate subject. 325 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Important The automatically generated self-signed certificates are valid by default for 10 years, but they have no automatic-renewal capability. Any modification to these certificates will require manually creating new certificates following guidelines provided by the OpenSSL or Mozilla NSS documentation on the subject. To configure client systems to trust the self-signed certificate, complete the following steps: 1. Copy the /etc/P eg asus/server. pem certificate from the managed system to the /etc/pki /ca-trust/so urce/ancho rs/ directory on the client system. To do so, type the following at a shell prompt as ro o t: scp ro o t@ hostname: /etc/P eg asus/server. pem /etc/pki /catrust/so urce/ancho rs/peg asus-hostname. pem Replace hostname with the host name of the managed system. Note that this command only works if the sshd service is running on the managed system and is configured to allow the ro o t user to log in to the system over the SSH protocol. For more information on how to install and configure the sshd service and use the scp command to transfer files over the SSH protocol, see Chapter 9, OpenSSH. 2. Verify the integrity of the certificate on the client system by comparing its checksum with the checksum of the original file. To calculate the checksum of the /etc/P eg asus/server. pem file on the managed system, run the following command as ro o t on that system: sha1sum /etc/P eg asus/server. pem To calculate the checksum of the /etc/pki /catrust/so urce/ancho rs/peg asus-hostname. pem file on the client system, run the following command on this system: sha1sum /etc/pki /ca-trust/so urce/ancho rs/peg asus-hostname. pem Replace hostname with the host name of the managed system. 3. Update the trust store on the client system by running the following command as ro o t: upd ate-ca-trust extract 19.3.2. Managing Aut horit y-signed Cert ificat es wit h Ident it y Management (Recommended) The Identity Management feature of Red Hat Enterprise Linux provides a domain controller which simplifies the management of SSL certificates within systems joined to the domain. Among others, the Identity Management server provides an embedded Certificate Authority. See the Red Hat Enterprise Linux 7 Linux D omain Identity, Authentication, and Policy Guide or the FreeIPA documentation for information on how to join the client and managed systems to the domain. It is necessary to register the managed system to Identity Management; for client systems the registration is optional. The following steps are required on the managed system: 326 Chapt er 1 9 . O penLMI 1. Install the ipa-client package and register the system to Identity Management as described in the Red Hat Enterprise Linux 7 Linux D omain Identity, Authentication, and Policy Guide. 2. Copy the Identity Management signing certificate to the trusted store by typing the following command as ro o t: cp /etc/i pa/ca. crt /etc/pki /ca-trust/so urce/ancho rs/i pa. crt 3. Update the trust store by running the following command as ro o t: upd ate-ca-trust extract 4. Register Pegasus as a service in the Identity Management domain by running the following command as a privileged domain user: i pa servi ce-ad d C IMO M/hostname Replace hostname with the host name of the managed system. This command can be run from any system in the Identity Management domain that has the ipa-admintools package installed. It creates a service entry in Identity Management that can be used to generate signed SSL certificates. 5. Back up the PEM files located in the /etc/P eg asus/ directory (recommended). 6. Retrieve the signed certificate by running the following command as ro o t: i pa-g etcert req uest -f /etc/P eg asus/server. pem -k /etc/P eg asus/fi l e. pem -N C N= hostname -K C IMO M/hostname Replace hostname with the host name of the managed system. The certificate and key files are now kept in proper locations. The certmo ng er daemon installed on the managed system by the i pa-cl i ent-i nstal l script ensures that the certificate is kept up-to-date and renewed as necessary. For more information, see the Red Hat Enterprise Linux 7 Linux D omain Identity, Authentication, and Policy Guide. To register the client system and update the trust store, follow the steps below. 1. Install the ipa-client package and register the system to Identity Management as described in the Red Hat Enterprise Linux 7 Linux D omain Identity, Authentication, and Policy Guide. 2. Copy the Identity Management signing certificate to the trusted store by typing the following command as ro o t: cp /etc/i pa/ca. crt /etc/pki /ca-trust/so urce/ancho rs/i pa. crt 3. Update the trust store by running the following command as ro o t: upd ate-ca-trust extract If the client system is not meant to be registered in Identity Management, complete the following steps to update the trust store. 327 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 1. Copy the /etc/i pa/ca. crt file securely from any other system joined to the same Identity Management domain to the trusted store /etc/pki /ca-trust/so urce/ancho rs/ directory as ro o t. 2. Update the trust store by running the following command as ro o t: upd ate-ca-trust extract 19.3.3. Managing Aut horit y-signed Cert ificat es Manually Managing authority-signed certificates with other mechanisms than Identity Management requires more manual configuration. It is necessary to ensure that all of the clients trust the certificate of the authority that will be signing the managed system certificates: If a certificate authority is trusted by default, it is not necessary to perform any particular steps to accomplish this. If the certificate authority is not trusted by default, the certificate has to be imported on the client and managed systems. Copy the certificate to the trusted store by typing the following command as ro o t: cp /path/to /ca. crt /etc/pki /ca-trust/so urce/ancho rs/ca. crt Update the trust store by running the following command as ro o t: upd ate-ca-trust extract On the managed system, complete the following steps: 1. Create a new SSL configuration file /etc/P eg asus/ssl . cnf to store information about the certificate. The contents of this file must be similar to the following example: [ req ] distinguished_name = prompt = [ req_distinguished_name C = ST = L = O = OU = CN = req_distinguished_name no ] US Massachusetts Westford Fedora Fedora OpenLMI hostname Replace hostname with the fully qualified domain name of the managed system. 2. Generate a private key on the managed system by using the following command as ro o t: o penssl g enrsa -o ut /etc/P eg asus/fi l e. pem 10 24 3. Generate a certificate signing request (CSR) by running this command as ro o t: 328 Chapt er 1 9 . O penLMI o penssl req -co nfi g /etc/P eg asus/ssl . cnf -new -key /etc/P eg asus/fi l e. pem -o ut /etc/P eg asus/server. csr 4. Send the /etc/P eg asus/server. csr file to the certificate authority for signing. The detailed procedure of submitting the file depends on the particular certificate authority. 5. When the signed certificate is received from the certificate authority, save it as /etc/P eg asus/server. pem. 6. Copy the certificate of the trusted authority to the Pegasus trust store to make sure that Pegasus is capable of trusting its own certificate by running as ro o t: cp /path/to /ca. crt /etc/P eg asus/cl i ent. pem After accomplishing all the described steps, the clients that trust the signing authority are able to successfully communicate with the managed server's CIMOM. Important Unlike the Identity Management solution, if the certificate expires and needs to be renewed, all of the described manual steps have to be carried out again. It is recommended to renew the certificates before they expire. 19.4 . Using LMIShell LMISh ell is an interactive client and non-interactive interpreter that can be used to access CIM objects provided by the OpenPegasus CIMOM. It is based on the Python interpreter, but also implements additional functions and classes for interacting with CIM objects. 19.4 .1. St art ing, Using, and Exit ing LMIShell Similarly to the Python interpreter, you can use LMIShell either as an interactive client, or as a noninteractive interpreter for LMIShell scripts. St art ing LMIShe ll in Int e ract ive Mo de To start the LMIShell interpreter in interactive mode, run the l mi shel l command with no additional arguments: l mi shel l By default, when LMIShell attempts to establish a connection with a CIMOM, it validates the serverside certificate against the Certification Authorities trust store. To disable this validation, run the l mi shel l command with the --no veri fy or -n command line option: l mi shel l --no veri fy Using T ab Co m ple t io n 329 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide When running in interactive mode, the LMIShell interpreter allows you press the T ab key to complete basic programming structures and CIM objects, including namespaces, classes, methods, and object properties. Bro wsing Hist o ry By default, LMIShell stores all commands you type at the interactive prompt in the ~ /. l mi shel l _hi sto ry file. This allows you to browse the command history and re-use already entered lines in interactive mode without the need to type them at the prompt again. To move backward in the command history, press the Up Arro w key or the C trl +p key combination. To move forward in the command history, press the D o wn Arro w key or the C trl +n key combination. LMIShell also supports an incremental reverse search. To look for a particular line in the command history, press C trl +r and start typing any part of the command. For example: > (reverse-i-search)`co nnect': c = co nnect("server. exampl e. co m", "peg asus") To clear the command history, use the cl ear_hi sto ry() function as follows: cl ear_hi sto ry() You can configure the number of lines that are stored in the command history by changing the value of the hi sto ry_l eng th option in the ~ /. l mi shel l rc configuration file. In addition, you can change the location of the history file by changing the value of the hi sto ry_fi l e option in this configuration file. For example, to set the location of the history file to ~ /. l mi shel l _hi sto ry and configure LMIShell to store the maximum of 10 0 0 lines in it, add the following lines to the ~ /. l mi shel l rc file: history_file = "~/.lmishell_history" history_length = 1000 Handling Exce pt io ns By default, the LMIShell interpreter handles all exceptions and uses return values. To disable this behavior in order to handle all exceptions in the code, use the use_excepti o ns() function as follows: use_excepti o ns() To re-enable the automatic exception handling, use: use_excepti o n(Fal se) You can permanently disable the exception handling by changing the value of the use_excepti o ns option in the ~ /. l mi shel l rc configuration file to T rue: use_exceptions = True Co nfiguring a T e m po rary Cache 330 Chapt er 1 9 . O penLMI With the default configuration, LMIShell connection objects use a temporary cache for storing CIM class names and CIM classes in order to reduce network communication. To clear this temporary cache, use the cl ear_cache() method as follows: object_name.cl ear_cache() Replace object_name with the name of a connection object. To disable the temporary cache for a particular connection object, use the use_cache() method as follows: object_name.use_cache(Fal se) To enable it again, use: object_name.use_cache(T rue) You can permanently disable the temporary cache for connection objects by changing the value of the use_cache option in the ~ /. l mi shel l rc configuration file to Fal se: use_cache = False Exit ing LMIShe ll To terminate the LMIShell interpreter and return to the shell prompt, press the C trl +d key combination or issue the q ui t() function as follows: > q ui t() ~]$ Running an LMIShe ll Script To run an LMIShell script, run the l mi shel l command as follows: l mi shel l file_name Replace file_name with the name of the script. To inspect an LMIShell script after its execution, also specify the --i nteract or -i command line option: l mi shel l --i nteract file_name The preferred file extension of LMIShell scripts is . l mi . 19.4 .2. Connect ing t o a CIMOM LMIShell allows you to connect to a CIMOM that is running either locally on the same system, or on a remote machine accessible over the network. Co nne ct ing t o a Re m o t e CIMOM To access CIM objects provided by a remote CIMOM, create a connection object by using the co nnect() function as follows: 331 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide co nnect(host_name, user_name[, password]) Replace host_name with the host name of the managed system, user_name with the name of a user that is allowed to connect to the OpenPegasus CIMOM running on that system, and password with the user's password. If the password is omitted, LMIShell prompts the user to enter it. The function returns an LMIC o nnecti o n object. Examp le 19 .1. C o n n ect in g t o a R emo t e C IMO M To connect to the OpenPegasus CIMOM running on server. exampl e. co m as user peg asus, type the following at the interactive prompt: > c = co nnect("server. exampl e. co m", "peg asus") password: > Co nne ct ing t o a Lo cal CIMOM LMIShell allows you to connect to a local CIMOM by using a Unix socket. For this type of connection, you must run the LMIShell interpreter as the ro o t user and the /var/run/to g peg asus/ci mxml . so cket socket must exist. To access CIM objects provided by a local CIMOM, create a connection object by using the co nnect() function as follows: co nnect(host_name) Replace host_name with l o cal ho st, 127. 0 . 0 . 1, or : : 1. The function returns an LMIC o nnecti o n object or No ne. Examp le 19 .2. C o n n ect in g t o a Lo cal C IMO M To connect to the OpenPegasus CIMOM running on l o cal ho st as the ro o t user, type the following at the interactive prompt: > c = co nnect("l o cal ho st") > Ve rifying a Co nne ct io n t o a CIMOM The co nnect() function returns either an LMIC o nnecti o n object, or No ne if the connection could not be established. In addition, when the co nnect() function fails to establish a connection, it prints an error message to standard error output. To verify that a connection to a CIMOM has been established successfully, use the i si nstance() function as follows: i si nstance(object_name, LMIC o nnecti o n) 332 Chapt er 1 9 . O penLMI Replace object_name with the name of the connection object. This function returns T rue if object_name is an LMIC o nnecti o n object, or Fal se otherwise. Examp le 19 .3. Verif yin g a C o n n ect io n t o a C IMO M To verify that the c variable created in Example 19.1, “ Connecting to a Remote CIMOM” contains an LMIC o nnecti o n object, type the following at the interactive prompt: > i si nstance(c, LMIC o nnecti o n) True > Alternatively, you can verify that c is not No ne: > c i s No ne False > 19.4 .3. Working wit h Namespaces LMIShell namespaces provide a natural means of organizing available classes and serve as a hierarchic access point to other namespaces and classes. The ro o t namespace is the first entry point of a connection object. List ing Available Nam e space s To list all available namespaces, use the pri nt_namespaces() method as follows: object_name.pri nt_namespaces() Replace object_name with the name of the object to inspect. This method prints available namespaces to standard output. To get a list of available namespaces, access the object attribute namespaces: object_name.namespaces This returns a list of strings. Examp le 19 .4 . List in g Availab le N amesp aces To inspect the ro o t namespace object of the c connection object created in Example 19.1, “ Connecting to a Remote CIMOM” and list all available namespaces, type the following at the interactive prompt: > c. ro o t. pri nt_namespaces() cimv2 interop PG_InterOp PG_Internal > 333 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To assign a list of these namespaces to a variable named ro o t_namespaces, type: > ro o t_namespaces = c. ro o t. namespaces > Acce ssing Nam e space Obje ct s To access a particular namespace object, use the following syntax: object_name.namespace_name Replace object_name with the name of the object to inspect and namespace_name with the name of the namespace to access. This returns an LMINamespace object. Examp le 19 .5. Accessin g N amesp ace O b ject s To access the ci mv2 namespace of the c connection object created in Example 19.1, “ Connecting to a Remote CIMOM” and assign it to a variable named ns, type the following at the interactive prompt: > ns = c. ro o t. ci mv2 > 19.4 .4 . Working wit h Classes LMIShell classes represent classes provided by a CIMOM. You can access and list their properties, methods, instances, instance names, and ValueMap properties, print their documentation strings, and create new instances and instance names. List ing Available Classe s To list all available classes in a particular namespace, use the pri nt_cl asses() method as follows: namespace_object.pri nt_cl asses() Replace namespace_object with the namespace object to inspect. This method prints available classes to standard output. To get a list of available classes, use the cl asses() method: namespace_object.cl asses() This method returns a list of strings. Examp le 19 .6 . List in g Availab le C lasses To inspect the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” and list all available classes, type the following at the interactive prompt: 334 Chapt er 1 9 . O penLMI > ns. pri nt_cl asses() CIM_CollectionInSystem CIM_ConcreteIdentity CIM_ControlledBy CIM_DeviceSAPImplementation CIM_MemberOfStatusCollection ... > To assign a list of these classes to a variable named ci mv2_cl asses, type: > ci mv2_cl asses = ns. cl asses() > Acce ssing Class Obje ct s To access a particular class object that is provided by the CIMOM, use the following syntax: namespace_object.class_name Replace namespace_object with the name of the namespace object to inspect and class_name with the name of the class to access. Examp le 19 .7. Accessin g C lass O b ject s To access the LMI_IP Netwo rkC o nnecti o n class of the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” and assign it to a variable named cl s, type the following at the interactive prompt: > cl s = ns. LMI_IP Netwo rkC o nnecti o n > Exam ining Class Obje ct s All class objects store information about their name and the namespace they belong to, as well as detailed class documentation. To get the name of a particular class object, use the following syntax: class_object.cl assname Replace class_object with the name of the class object to inspect. This returns a string representation of the object name. To get information about the namespace a class object belongs to, use: class_object.namespace This returns a string representation of the namespace. To display detailed class documentation, use the d o c() method as follows: class_object.d o c() 335 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Examp le 19 .8. Examin in g C lass O b ject s To inspect the cl s class object created in Example 19.7, “ Accessing Class Objects” and display its name and corresponding namespace, type the following at the interactive prompt: > cl s. cl assname 'LMI_IPNetworkConnection' > cl s. namespace 'root/cimv2' > To access class documentation, type: > cl s. d o c() Class: LMI_IPNetworkConnection SuperClass: CIM_IPNetworkConnection [qualifier] string UMLPackagePath: 'CIM::Network::IP' [qualifier] string Version: '0.1.0' ... List ing Available Me t ho ds To list all available methods of a particular class object, use the pri nt_metho d s() method as follows: class_object.pri nt_metho d s() Replace class_object with the name of the class object to inspect. This method prints available methods to standard output. To get a list of available methods, use the metho d s() method: class_object.metho d s() This method returns a list of strings. Examp le 19 .9 . List in g Availab le Met h o d s To inspect the cl s class object created in Example 19.7, “ Accessing Class Objects” and list all available methods, type the following at the interactive prompt: > cl s. pri nt_metho d s() RequestStateChange > To assign a list of these methods to a variable named servi ce_metho d s, type: > servi ce_metho d s = cl s. metho d s() > 336 Chapt er 1 9 . O penLMI List ing Available Pro pe rt ie s To list all available properties of a particular class object, use the pri nt_pro perti es() method as follows: class_object.pri nt_pro perti es() Replace class_object with the name of the class object to inspect. This method prints available properties to standard output. To get a list of available properties, use the pro perti es() method: class_object.pro perti es() This method returns a list of strings. Examp le 19 .10. List in g Availab le Pro p ert ies To inspect the cl s class object created in Example 19.7, “ Accessing Class Objects” and list all available properties, type the following at the interactive prompt: > cl s. pri nt_pro perti es() RequestedState HealthState StatusDescriptions TransitioningToState Generation ... > To assign a list of these classes to a variable named servi ce_pro perti es, type: > servi ce_pro perti es = cl s. pro perti es() > List ing and Vie wing Value Map Pro pe rt ie s CIM classes may contain ValueMap properties in their Managed Object Format (MOF) definition. ValueMap properties contain constant values, which may be useful when calling methods or checking returned values. To list all available ValueMap properties of a particular class object, use the pri nt_val uemap_pro perti es() method as follows: class_object.pri nt_val uemap_pro perti es() Replace class_object with the name of the class object to inspect. This method prints available ValueMap properties to standard output: To get a list of available ValueMap properties, use the val uemap_pro perti es() method: 337 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide class_object.val uemap_pro perti es() This method returns a list of strings. Examp le 19 .11. List in g Valu eMap Pro p ert ies To inspect the cl s class object created in Example 19.7, “ Accessing Class Objects” and list all available ValueMap properties, type the following at the interactive prompt: > cl s. pri nt_val uemap_pro perti es() RequestedState HealthState TransitioningToState DetailedStatus OperationalStatus ... > To assign a list of these ValueMap properties to a variable named servi ce_val uemap_pro perti es, type: > servi ce_val uemap_pro perti es = cl s. val uemap_pro perti es() > To access a particular ValueMap property, use the following syntax: class_object.valuemap_propertyVal ues Replace valuemap_property with the name of the ValueMap property to access. To list all available constant values, use the pri nt_val ues() method as follows: class_object.valuemap_propertyVal ues.pri nt_val ues() This method prints available named constant values to standard output. You can also get a list of available constant values by using the val ues() method: class_object.valuemap_propertyVal ues.val ues() This method returns a list of strings. Examp le 19 .12. Accessin g Valu eMap Pro p ert ies Example 19.11, “ Listing ValueMap Properties” mentions a ValueMap property named R eq uested State. To inspect this property and list available constant values, type the following at the interactive prompt: > cl s. R eq uested StateVal ues. pri nt_val ues() Reset NoChange NotApplicable 338 Chapt er 1 9 . O penLMI Quiesce Unknown ... > To assign a list of these constant values to a variable named req uested _state_val ues, type: > req uested _state_val ues = cl s. R eq uested StateVal ues. val ues() > To access a particular constant value, use the following syntax: class_object.valuemap_propertyVal ues.constant_value_name Replace constant_value_name with the name of the constant value. Alternatively, you can use the val ue() method as follows: class_object.valuemap_propertyVal ues.val ue("constant_value_name") To determine the name of a particular constant value, use the val ue_name() method: class_object.valuemap_propertyVal ues.val ue_name("constant_value") This method returns a string. Examp le 19 .13. Accessin g C o n st an t Valu es Example 19.12, “ Accessing ValueMap Properties” shows that the R eq uested State property provides a constant value named R eset. To access this named constant value, type the following at the interactive prompt: > cl s. R eq uested StateVal ues. R eset 11 > cl s. R eq uested StateVal ues. val ue("R eset") 11 > To determine the name of this constant value, type: > cl s. R eq uested StateVal ues. val ue_name(11) u'Reset' > Fe t ching a CIMClass Obje ct Many class methods do not require access to a C IMC l ass object, which is why LMIShell only fetches this object from the CIMOM when a called method actually needs it. To fetch the C IMC l ass object manually, use the fetch() method as follows: class_object.fetch() 339 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Replace class_object with the name of the class object. Note that methods that require access to a C IMC l ass object fetch it automatically. 19.4 .5. Working wit h Inst ances LMIShell instances represent instances provided by a CIMOM. You can get and set their properties, list and call their methods, print their documentation strings, get a list of associated or association objects, push modified objects to the CIMOM, and delete individual instances from the CIMOM. Acce ssing Inst ance s To get a list of all available instances of a particular class object, use the i nstances() method as follows: class_object.i nstances() Replace class_object with the name of the class object to inspect. This method returns a list of LMIInstance objects. To access the first instance of a class object, use the fi rst_i nstance() method: class_object.fi rst_i nstance() This method returns an LMIInstance object. In addition to listing all instances or returning the first one, both i nstances() and fi rst_i nstance() support an optional argument to allow you to filter the results: class_object.i nstances(criteria) class_object.fi rst_i nstance(criteria) Replace criteria with a dictionary consisting of key-value pairs, where keys represent instance properties and values represent required values of these properties. Examp le 19 .14 . Accessin g In st an ces To find the first instance of the cl s class object created in Example 19.7, “ Accessing Class Objects” that has the El ementName property equal to eth0 and assign it to a variable named d evi ce, type the following at the interactive prompt: > d evi ce = cl s. fi rst_i nstance({"El ementName": "eth0 "}) > Exam ining Inst ance s All instance objects store information about their class name and the namespace they belong to, as well as detailed documentation about their properties and values. In addition, instance objects allow you to retrieve a unique identification object. To get the class name of a particular instance object, use the following syntax: 34 0 Chapt er 1 9 . O penLMI instance_object.cl assname Replace instance_object with the name of the instance object to inspect. This returns a string representation of the class name. To get information about the namespace an instance object belongs to, use: instance_object.namespace This returns a string representation of the namespace. To retrieve a unique identification object for an instance object, use: instance_object.path This returns an LMIInstanceName object. Finally, to display detailed documentation, use the d o c() method as follows: instance_object.d o c() Examp le 19 .15. Examin in g In st an ces To inspect the d evi ce instance object created in Example 19.14, “ Accessing Instances” and display its class name and the corresponding namespace, type the following at the interactive prompt: > d evi ce. cl assname u'LMI_IPNetworkConnection' > d evi ce. namespace 'root/cimv2' > To access instance object documentation, type: > d evi ce. d o c() Instance of LMI_IPNetworkConnection [property] uint16 RequestedState = '12' [property] uint16 HealthState [property array] string [] StatusDescriptions ... Cre at ing Ne w Inst ance s Certain CIM providers allow you to create new instances of specific classes objects. To create a new instance of a class object, use the create_i nstance() method as follows: class_object.create_i nstance(properties) 34 1 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Replace class_object with the name of the class object and properties with a dictionary that consists of key-value pairs, where keys represent instance properties and values represent property values. This method returns an LMIInstance object. Examp le 19 .16 . C reat in g N ew In st an ces The LMI_G ro up class represents system groups and the LMI_Acco unt class represents user accounts on the managed system. To use the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” , create instances of these two classes for the system group named peg asus and the user named l mi shel l -user, and assign them to variables named g ro up and user, type the following at the interactive prompt: > g ro up = ns. LMI_G ro up. fi rst_i nstance({"Name" : "peg asus"}) > user = ns. LMI_Acco unt. fi rst_i nstance({"Name" : "l mi shel l -user"}) > To get an instance of the LMI_Id enti ty class for the l mi shel l -user user, type: > i d enti ty = user. fi rst_asso ci ato r(R esul tC l ass= "LMI_Id enti ty") > The LMI_MemberO fG ro up class represents system group membership. To use the LMI_MemberO fG ro up class to add the l mi shel l -user to the peg asus group, create a new instance of this class as follows: > ns. LMI_MemberO fG ro up. create_i nstance({ ... "Member" : i d enti ty. path, ... "C o l l ecti o n" : g ro up. path}) LMIInstance(classname="LMI_MemberOfGroup", ...) > De le t ing Individual Inst ance s To delete a particular instance from the CIMOM, use the d el ete() method as follows: instance_object.d el ete() Replace instance_object with the name of the instance object to delete. This method returns a boolean. Note that after deleting an instance, its properties and methods become inaccessible. Examp le 19 .17. D elet in g In d ivid u al In st an ces The LMI_Acco unt class represents user accounts on the managed system. To use the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” , create an instance of the LMI_Acco unt class for the user named l mi shel l -user, and assign it to a variable named user, type the following at the interactive prompt: > user = ns. LMI_Acco unt. fi rst_i nstance({"Name" : "l mi shel l -user"}) > To delete this instance and remove the l mi shel l -user from the system, type: 34 2 Chapt er 1 9 . O penLMI > user. d el ete() True > List ing and Acce ssing Available Pro pe rt ie s To list all available properties of a particular instance object, use the pri nt_pro perti es() method as follows: instance_object.pri nt_pro perti es() Replace instance_object with the name of the instance object to inspect. This method prints available properties to standard output. To get a list of available properties, use the pro perti es() method: instance_object.pro perti es() This method returns a list of strings. Examp le 19 .18. List in g Availab le Pro p ert ies To inspect the d evi ce instance object created in Example 19.14, “ Accessing Instances” and list all available properties, type the following at the interactive prompt: > d evi ce. pri nt_pro perti es() RequestedState HealthState StatusDescriptions TransitioningToState Generation ... > To assign a list of these properties to a variable named d evi ce_pro perti es, type: > d evi ce_pro perti es = d evi ce. pro perti es() > To get the current value of a particular property, use the following syntax: instance_object.property_name Replace property_name with the name of the property to access. To modify the value of a particular property, assign a value to it as follows: instance_object.property_name = value Replace value with the new value of the property. Note that in order to propagate the change to the CIMOM, you must also execute the push() method: 34 3 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide instance_object.push() This method returns a three-item tuple consisting of a return value, return value parameters, and an error string. Examp le 19 .19 . Accessin g In d ivid u al Pro p ert ies To inspect the d evi ce instance object created in Example 19.14, “ Accessing Instances” and display the value of the property named SystemName, type the following at the interactive prompt: > d evi ce. SystemName u'server.example.com' > List ing and Using Available Me t ho ds To list all available methods of a particular instance object, use the pri nt_metho d s() method as follows: instance_object.pri nt_metho d s() Replace instance_object with the name of the instance object to inspect. This method prints available methods to standard output. To get a list of available methods, use the metho d () method: instance_object.metho d s() This method returns a list of strings. Examp le 19 .20. List in g Availab le Met h o d s To inspect the d evi ce instance object created in Example 19.14, “ Accessing Instances” and list all available methods, type the following at the interactive prompt: > d evi ce. pri nt_metho d s() RequestStateChange > To assign a list of these methods to a variable named netwo rk_d evi ce_metho d s, type: > netwo rk_d evi ce_metho d s = d evi ce. metho d s() > To call a particular method, use the following syntax: instance_object.method_name( parameter=value, ...) 34 4 Chapt er 1 9 . O penLMI Replace instance_object with the name of the instance object to use, method_name with the name of the method to call, parameter with the name of the parameter to set, and value with the value of this parameter. Methods return a three-item tuple consisting of a return value, return value parameters, and an error string. Important LMIInstance objects do n o t automatically refresh their contents (properties, methods, qualifiers, and so on). To do so, use the refresh() method as described below. Examp le 19 .21. U sin g Met h o d s The P G _C o mputerSystem class represents the system. To create an instance of this class by using the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” and assign it to a variable named sys, type the following at the interactive prompt: > sys = ns. P G _C o mputerSystem. fi rst_i nstance() > The LMI_Acco untManag ementServi ce class implements methods that allow you to manage users and groups in the system. To create an instance of this class and assign it to a variable named acc, type: > acc = ns. LMI_Acco untManag ementServi ce. fi rst_i nstance() > To create a new user named l mi shel l -user in the system, use the C reateAcco unt() method as follows: > acc. C reateAcco unt(Name= "l mi shel l -user", System= sys) LMIReturnValue(rval=0, rparams=NocaseDict({u'Account': LMIInstanceName(classname="LMI_Account"...), u'Identities': [LMIInstanceName(classname="LMI_Identity"...), LMIInstanceName(classname="LMI_Identity"...)]}), errorstr='') LMIShell support synchronous method calls: when you use a synchronous method, LMIShell waits for the corresponding Job object to change its state to “ finished” and then returns the return parameters of this job. LMIShell is able to perform a synchronous method call if the given method returns an object of one of the following classes: LMI_Sto rag eJo b LMI_So ftwareInstal l ati o nJo b LMI_Netwo rkJo b LMIShell first tries to use indications as the waiting method. If it fails, it uses a polling method instead. To perform a synchronous method call, use the following syntax: 34 5 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide instance_object.Syncmethod_name( parameter=value, ...) Replace instance_object with the name of the instance object to use, method_name with the name of the method to call, parameter with the name of the parameter to set, and value with the value of this parameter. All synchronous methods have the Sync prefix in their name and return a three-item tuple consisting of the job's return value, job's return value parameters, and job's error string. You can also force LMIShell to use only polling method. To do so, specify the P referP o l l i ng parameter as follows: instance_object.Syncmethod_name( P referP o l l i ng =T rue parameter=value, ...) List ing and Vie wing Value Map Param e t e rs CIM methods may contain ValueMap parameters in their Managed Object Format (MOF) definition. ValueMap parameters contain constant values. To list all available ValueMap parameters of a particular method, use the pri nt_val uemap_parameters() method as follows: instance_object.method_name.pri nt_val uemap_parameters() Replace instance_object with the name of the instance object and method_name with the name of the method to inspect. This method prints available ValueMap parameters to standard output. To get a list of available ValueMap parameters, use the val uemap_parameters() method: instance_object.method_name.val uemap_parameters() This method returns a list of strings. Examp le 19 .22. List in g Valu eMap Paramet ers To inspect the acc instance object created in Example 19.21, “ Using Methods” and list all available ValueMap parameters of the C reateAcco unt() method, type the following at the interactive prompt: > acc. C reateAcco unt. pri nt_val uemap_parameters() CreateAccount > To assign a list of these ValueMap parameters to a variable named create_acco unt_parameters, type: > create_acco unt_parameters = acc. C reateAcco unt. val uemap_parameters() > 34 6 Chapt er 1 9 . O penLMI To access a particular ValueMap parameter, use the following syntax: instance_object.method_name.valuemap_parameterVal ues Replace valuemap_parameter with the name of the ValueMap parameter to access. To list all available constant values, use the pri nt_val ues() method as follows: instance_object.method_name.valuemap_parameterVal ues.pri nt_val ues() This method prints available named constant values to standard output. You can also get a list of available constant values by using the val ues() method: instance_object.method_name.valuemap_parameterVal ues.val ues() This method returns a list of strings. Examp le 19 .23. Accessin g Valu eMap Paramet ers Example 19.22, “ Listing ValueMap Parameters” mentions a ValueMap parameter named C reateAcco unt. To inspect this parameter and list available constant values, type the following at the interactive prompt: > acc. C reateAcco unt. C reateAcco untVal ues. pri nt_val ues() Operationunsupported Failed Unabletosetpasswordusercreated Unabletocreatehomedirectoryusercreatedandpasswordset Operationcompletedsuccessfully > To assign a list of these constant values to a variable named create_acco unt_val ues, type: > create_acco unt_val ues = acc. C reateAcco unt. C reateAcco untVal ues. val ues() > To access a particular constant value, use the following syntax: instance_object.method_name.valuemap_parameterVal ues.constant_value_name Replace constant_value_name with the name of the constant value. Alternatively, you can use the val ue() method as follows: instance_object.method_name.valuemap_parameterVal ues.val ue("constant_val ue_name") To determine the name of a particular constant value, use the val ue_name() method: instance_object.method_name.valuemap_parameterVal ues.val ue_name("constan t_value") 34 7 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide This method returns a string. Examp le 19 .24 . Accessin g C o n st an t Valu es Example 19.23, “ Accessing ValueMap Parameters” shows that the C reateAcco unt ValueMap parameter provides a constant value named Fai l ed . To access this named constant value, type the following at the interactive prompt: > acc. C reateAcco unt. C reateAcco untVal ues. Fai l ed 2 > acc. C reateAcco unt. C reateAcco untVal ues. val ue("Fai l ed ") 2 > To determine the name of this constant value, type: > acc. C reateAcco unt. C reateAcco untVal ues. val ue_name(2) u'Failed' > Re fre shing Inst ance Obje ct s Local objects used by LMIShell, which represent CIM objects at CIMOM side, can get outdated, if such objects change while working with LMIShell's ones. To update the properties and methods of a particular instance object, use the refresh() method as follows: instance_object.refresh() Replace instance_object with the name of the object to refresh. This method returns a three-item tuple consisting of a return value, return value parameter, and an error string. Examp le 19 .25. R ef resh in g In st an ce O b ject s To update the properties and methods of the d evi ce instance object created in Example 19.14, “ Accessing Instances” , type the following at the interactive prompt: > d evi ce. refresh() LMIReturnValue(rval=True, rparams=NocaseDict({}), errorstr='') > Displaying MOF Re pre se nt at io n To display the Managed Object Format (MOF) representation of an instance object, use the to mo f() method as follows: instance_object.to mo f() Replace instance_object with the name of the instance object to inspect. This method prints the MOF representation of the object to standard output. 34 8 Chapt er 1 9 . O penLMI Examp le 19 .26 . D isp layin g MO F R ep resen t at io n To display the MOF representation of the d evi ce instance object created in Example 19.14, “ Accessing Instances” , type the following at the interactive prompt: > d evi ce. to mo f() instance of LMI_IPNetworkConnection { RequestedState = 12; HealthState = NULL; StatusDescriptions = NULL; TransitioningToState = 12; ... 19.4 .6. Working wit h Inst ance Names LMIShell instance names are objects that hold a set of primary keys and their values. This type of an object exactly identifies an instance. Acce ssing Inst ance Nam e s C IMInstance objects are identified by C IMInstanceName objects. To get a list of all available instance name objects, use the i nstance_names() method as follows: class_object.i nstance_names() Replace class_object with the name of the class object to inspect. This method returns a list of LMIInstanceName objects. To access the first instance name object of a class object, use the fi rst_i nstance_name() method: class_object.fi rst_i nstance_name() This method returns an LMIInstanceName object. In addition to listing all instance name objects or returning the first one, both i nstance_names() and fi rst_i nstance_name() support an optional argument to allow you to filter the results: class_object.i nstance_names(criteria) class_object.fi rst_i nstance_name(criteria) Replace criteria with a dictionary consisting of key-value pairs, where keys represent key properties and values represent required values of these key properties. Examp le 19 .27. Accessin g In st an ce N ames To find the first instance name of the cl s class object created in Example 19.7, “ Accessing Class Objects” that has the Name key property equal to eth0 and assign it to a variable named d evi ce_name, type the following at the interactive prompt: 34 9 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide > d evi ce_name = cl s. fi rst_i nstance_name({"Name": "eth0 "}) > Exam ining Inst ance Nam e s All instance name objects store information about their class name and the namespace they belong to. To get the class name of a particular instance name object, use the following syntax: instance_name_object.cl assname Replace instance_name_object with the name of the instance name object to inspect. This returns a string representation of the class name. To get information about the namespace an instance name object belongs to, use: instance_name_object.namespace This returns a string representation of the namespace. Examp le 19 .28. Examin in g In st an ce N ames To inspect the d evi ce_name instance name object created in Example 19.27, “ Accessing Instance Names” and display its class name and the corresponding namespace, type the following at the interactive prompt: > d evi ce_name. cl assname u'LMI_IPNetworkConnection' > d evi ce_name. namespace 'root/cimv2' > Cre at ing Ne w Inst ance Nam e s LMIShell allows you to create a new wrapped C IMInstanceName object if you know all primary keys of a remote object. This instance name object can then be used to retrieve the whole instance object. To create a new instance name of a class object, use the new_i nstance_name() method as follows: class_object.new_i nstance_name(key_properties) Replace class_object with the name of the class object and key_properties with a dictionary that consists of key-value pairs, where keys represent key properties and values represent key property values. This method returns an LMIInstanceName object. Examp le 19 .29 . C reat in g N ew In st an ce N ames 350 Chapt er 1 9 . O penLMI The LMI_Acco unt class represents user accounts on the managed system. To use the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” and create a new instance name of the LMI_Acco unt class representing the l mi shel l -user user on the managed system, type the following at the interactive prompt: > i nstance_name = ns. LMI_Acco unt. new_i nstance_name({ ... "C reati o nC l assName" : "LMI_Acco unt", ... "Name" : "l mi shel l -user", ... "SystemC reati o nC l assName" : "P G _C o mputerSystem", ... "SystemName" : "server"}) > List ing and Acce ssing Ke y Pro pe rt ie s To list all available key properties of a particular instance name object, use the pri nt_key_pro perti es() method as follows: instance_name_object.pri nt_key_pro perti es() Replace instance_name_object with the name of the instance name object to inspect. This method prints available key properties to standard output. To get a list of available key properties, use the key_pro perti es() method: instance_name_object.key_pro perti es() This method returns a list of strings. Examp le 19 .30. List in g Availab le K ey Pro p ert ies To inspect the d evi ce_name instance name object created in Example 19.27, “ Accessing Instance Names” and list all available key properties, type the following at the interactive prompt: > d evi ce_name. pri nt_key_pro perti es() CreationClassName SystemName Name SystemCreationClassName > To assign a list of these key properties to a variable named d evi ce_name_pro perti es, type: > d evi ce_name_pro perti es = d evi ce_name. key_pro perti es() > To get the current value of a particular key property, use the following syntax: instance_name_object.key_property_name Replace key_property_name with the name of the key property to access. 351 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Examp le 19 .31. Accessin g In d ivid u al K ey Pro p ert ies To inspect the d evi ce_name instance name object created in Example 19.27, “ Accessing Instance Names” and display the value of the key property named SystemName, type the following at the interactive prompt: > d evi ce_name. SystemName u'server.example.com' > Co nve rt ing Inst ance Nam e s t o Inst ance s Each instance name can be converted to an instance. To do so, use the to _i nstance() method as follows: instance_name_object.to _i nstance() Replace instance_name_object with the name of the instance name object to convert. This method returns an LMIInstance object. Examp le 19 .32. C o n vert in g In st an ce N ames t o In st an ces To convert the d evi ce_name instance name object created in Example 19.27, “ Accessing Instance Names” to an instance object and assign it to a variable named d evi ce, type the following at the interactive prompt: > d evi ce = d evi ce_name. to _i nstance() > 19.4 .7. Working wit h Associat ed Object s The Common Information Model defines an association relationship between managed objects. Acce ssing Asso ciat e d Inst ance s To get a list of all objects associated with a particular instance object, use the asso ci ato rs() method as follows: instance_object.asso ci ato rs( Asso cC l ass=class_name, R esul tC l ass=class_name, R esul tR o l e=role, Incl ud eQ ual i fi ers=include_qualifiers, Incl ud eC l assO ri g i n=include_class_origin, P ro pertyLi st=property_list) To access the first object associated with a particular instance object, use the fi rst_asso ci ato r() method: instance_object.fi rst_asso ci ato r( Asso cC l ass=class_name, 352 Chapt er 1 9 . O penLMI R esul tC l ass=class_name, R esul tR o l e=role, Incl ud eQ ual i fi ers=include_qualifiers, Incl ud eC l assO ri g i n=include_class_origin, P ro pertyLi st=property_list) Replace instance_object with the name of the instance object to inspect. You can filter the results by specifying the following parameters: Asso cC l ass — Each returned object must be associated with the source object through an instance of this class or one of its subclasses. The default value is No ne. R esul tC l ass — Each returned object must be either an instance of this class or one of its subclasses, or it must be this class or one of its subclasses. The default value is No ne. R o l e — Each returned object must be associated with the source object through an association in which the source object plays the specified role. The name of the property in the association class that refers to the source object must match the value of this parameter. The default value is No ne. R esul tR o l e — Each returned object must be associated with the source object through an association in which the returned object plays the specified role. The name of the property in the association class that refers to the returned object must match the value of this parameter. The default value is No ne. The remaining parameters refer to: Incl ud eQ ual i fi ers — A boolean indicating whether all qualifiers of each object (including qualifiers on the object and on any returned properties) should be included as QUALIFIER elements in the response. The default value is Fal se. Incl ud eC l assO ri g i n — A boolean indicating whether the CLASSORIGIN attribute should be present on all appropriate elements in each returned object. The default value is Fal se. P ro pertyLi st — The members of this list define one or more property names. Returned objects will not include elements for any properties missing from this list. If P ro pertyLi st is an empty list, no properties are included in returned objects. If it is No ne, no additional filtering is defined. The default value is No ne. Examp le 19 .33. Accessin g Asso ciat ed In st an ces The LMI_Sto rag eExtent class represents block devices available in the system. To use the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” , create an instance of the LMI_Sto rag eExtent class for the block device named /d ev/vd a, and assign it to a variable named vd a, type the following at the interactive prompt: > vd a = ns. LMI_Sto rag eExtent. fi rst_i nstance({ ... "D evi ceID " : "/d ev/vd a"}) > To get a list of all disk partitions on this block device and assign it to a variable named vd a_parti ti o ns, use the asso ci ato rs() method as follows: > vd a_parti ti o ns = vd a. asso ci ato rs(R esul tC l ass= "LMI_D i skP arti ti o n") > 353 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Acce ssing Asso ciat e d Inst ance Nam e s To get a list of all associated instance names of a particular instance object, use the asso ci ato r_names() method as follows: instance_object.asso ci ato r_names( Asso cC l ass=class_name, R esul tC l ass=class_name, R o l e=role, R esul tR o l e=role) To access the first associated instance name of a particular instance object, use the fi rst_asso ci ato r_name() method: instance_object.fi rst_asso ci ato r_name( Asso cC l ass=class_object, R esul tC l ass=class_object, R o l e=role, R esul tR o l e=role) Replace instance_object with the name of the instance object to inspect. You can filter the results by specifying the following parameters: Asso cC l ass — Each returned name identifies an object that must be associated with the source object through an instance of this class or one of its subclasses. The default value is No ne. R esul tC l ass — Each returned name identifies an object that must be either an instance of this class or one of its subclasses, or it must be this class or one of its subclasses. The default value is No ne. R o l e — Each returned name identifies an object that must be associated with the source object through an association in which the source object plays the specified role. The name of the property in the association class that refers to the source object must match the value of this parameter. The default value is No ne. R esul tR o l e — Each returned name identifies an object that must be associated with the source object through an association in which the returned named object plays the specified role. The name of the property in the association class that refers to the returned object must match the value of this parameter. The default value is No ne. Examp le 19 .34 . Accessin g Asso ciat ed In st an ce N ames To use the vd a instance object created in Example 19.33, “ Accessing Associated Instances” , get a list of its associated instance names, and assign it to a variable named vd a_parti ti o ns, type: > vd a_parti ti o ns = vd a. asso ci ato r_names(R esul tC l ass= "LMI_D i skP arti ti o n") > 19.4 .8. Working wit h Associat ion Object s The Common Information Model defines an association relationship between managed objects. Association objects define the relationship between two other objects. 354 Chapt er 1 9 . O penLMI Acce ssing Asso ciat io n Inst ance s To get a list of association objects that refer to a particular target object, use the references() method as follows: instance_object.references( R esul tC l ass=class_name, R o l e=role, Incl ud eQ ual i fi ers=include_qualifiers, Incl ud eC l assO ri g i n=include_class_origin, P ro pertyLi st=property_list) To access the first association object that refers to a particular target object, use the fi rst_reference() method: instance_object.fi rst_reference( ... R esul tC l ass=class_name, ... R o l e=role, ... Incl ud eQ ual i fi ers=include_qualifiers, ... Incl ud eC l assO ri g i n=include_class_origin, ... P ro pertyLi st=property_list) > Replace instance_object with the name of the instance object to inspect. You can filter the results by specifying the following parameters: R esul tC l ass — Each returned object must be either an instance of this class or one of its subclasses, or it must be this class or one of its subclasses. The default value is No ne. R o l e — Each returned object must refer to the target object through a property with a name that matches the value of this parameter. The default value is No ne. The remaining parameters refer to: Incl ud eQ ual i fi ers — A boolean indicating whether each object (including qualifiers on the object and on any returned properties) should be included as a QUALIFIER element in the response. The default value is Fal se. Incl ud eC l assO ri g i n — A boolean indicating whether the CLASSORIGIN attribute should be present on all appropriate elements in each returned object. The default value is Fal se. P ro pertyLi st — The members of this list define one or more property names. Returned objects will not include elements for any properties missing from this list. If P ro pertyLi st is an empty list, no properties are included in returned objects. If it is No ne, no additional filtering is defined. The default value is No ne. Examp le 19 .35. Accessin g Asso ciat io n In st an ces The LMI_LANEnd po i nt class represents a communication endpoint associated with a certain network interface device. To use the ns namespace object created in Example 19.5, “ Accessing Namespace Objects” , create an instance of the LMI_LANEnd po i nt class for the network interface device named eth0, and assign it to a variable named l an_end po i nt, type the following at the interactive prompt: 355 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide > l an_end po i nt = ns. LMI_LANEnd po i nt. fi rst_i nstance({ ... "Name" : "eth0 "}) > To access the first association object that refers to an LMI_Bi nd sT o LANEnd po i nt object and assign it to a variable named bi nd , type: > bi nd = l an_end po i nt. fi rst_reference( ... R esul tC l ass= "LMI_Bi nd sT o LANEnd po i nt") > You can now use the D epend ent property to access the dependent LMI_IP P ro to co l End po i nt class that represents the IP address of the corresponding network interface device: > i p = bi nd . D epend ent. to _i nstance() > pri nt i p. IP v4 Ad d ress 192.168.122.1 > Acce ssing Asso ciat io n Inst ance Nam e s To get a list of association instance names of a particular instance object, use the reference_names() method as follows: instance_object.reference_names( R esul tC l ass=class_name, R o l e=role) To access the first association instance name of a particular instance object, use the fi rst_reference_name() method: instance_object.fi rst_reference_name( R esul tC l ass=class_name, R o l e=role) Replace instance_object with the name of the instance object to inspect. You can filter the results by specifying the following parameters: R esul tC l ass — Each returned object name identifies either an instance of this class or one of its subclasses, or this class or one of its subclasses. The default value is No ne. R o l e — Each returned object identifies an object that refers to the target instance through a property with a name that matches the value of this parameter. The default value is No ne. Examp le 19 .36 . Accessin g Asso ciat io n In st an ce N ames To use the l an_end po i nt instance object created in Example 19.35, “ Accessing Association Instances” , access the first association instance name that refers to an LMI_Bi nd sT o LANEnd po i nt object, and assign it to a variable named bi nd , type: 356 Chapt er 1 9 . O penLMI > bi nd = l an_end po i nt. fi rst_reference_name( ... R esul tC l ass= "LMI_Bi nd sT o LANEnd po i nt") You can now use the D epend ent property to access the dependent LMI_IP P ro to co l End po i nt class that represents the IP address of the corresponding network interface device: > i p = bi nd . D epend ent. to _i nstance() > pri nt i p. IP v4 Ad d ress 192.168.122.1 > 19.4 .9. Working wit h Indicat ions Indication is a reaction to a specific event that occurs in response to a particular change in data. LMIShell can subscribe to an indication in order to receive such event responses. Subscribing t o Indicat io ns To subscribe to an indication, use the subscri be_i nd i cati o n() method as follows: connection_object.subscri be_i nd i cati o n( Q ueryLang uag e="WQ L", Q uery=' SELEC T * FR O M C IM_InstMo d i fi cati o n' , Name="cpu", C reati o nNamespace="ro o t/i ntero p", Subscri pti o nC reati o nC l assName="C IM_Ind i cati o nSubscri pti o n", Fi l terC reati o nC l assName="C IM_Ind i cati o nFi l ter", Fi l terSystemC reati o nC l assName="C IM_C o mputerSystem", Fi l terSo urceNamespace="ro o t/ci mv2", Hand l erC reati o nC l assName="C IM_Ind i cati o nHand l erC IMXML", Hand l erSystemC reati o nC l assName="C IM_C o mputerSystem", D esti nati o n="http: //host_name: 59 88") Alternatively, you can use a shorter version of the method call as follows: connection_object.subscri be_i nd i cati o n( Q uery=' SELEC T * FR O M C IM_InstMo d i fi cati o n' , Name="cpu", D esti nati o n="http: //host_name: 59 88") Replace connection_object with a connection object and host_name with the host name of the system you want to deliver the indications to. By default, all subscriptions created by the LMIShell interpreter are automatically deleted when the interpreter terminates. To change this behavior, pass the P ermanent= T rue keyword parameter to the subscri be_i nd i cati o n() method call. This will prevent LMIShell from deleting the subscription. Examp le 19 .37. Su b scrib in g t o In d icat io n s 357 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To use the c connection object created in Example 19.1, “ Connecting to a Remote CIMOM” and subscribe to an indication named cpu, type the following at the interactive prompt: > c. subscri be_i nd i cati o n( ... Q ueryLang uag e= "WQ L", ... Q uery= ' SELEC T * FR O M C IM_InstMo d i fi cati o n' , ... Name= "cpu", ... C reati o nNamespace= "ro o t/i ntero p", ... Subscri pti o nC reati o nC l assName= "C IM_Ind i cati o nSubscri pti o n", ... Fi l terC reati o nC l assName= "C IM_Ind i cati o nFi l ter", ... Fi l terSystemC reati o nC l assName= "C IM_C o mputerSystem", ... Fi l terSo urceNamespace= "ro o t/ci mv2", ... Hand l erC reati o nC l assName= "C IM_Ind i cati o nHand l erC IMXML", ... Hand l erSystemC reati o nC l assName= "C IM_C o mputerSystem", ... D esti nati o n= "http: //server. exampl e. co m: 59 88") LMIReturnValue(rval=True, rparams=NocaseDict({}), errorstr='') > List ing Subscribe d Indicat io ns To list all the subscribed indications, use the pri nt_subscri bed _i nd i cati o ns() method as follows: connection_object.pri nt_subscri bed _i nd i cati o ns() Replace connection_object with the name of the connection object to inspect. This method prints subscribed indications to standard output. To get a list of subscribed indications, use the subscri bed _i nd i cati o ns() method: connection_object.subscri bed _i nd i cati o ns() This method returns a list of strings. Examp le 19 .38. List in g Su b scrib ed In d icat io n s To inspect the c connection object created in Example 19.1, “ Connecting to a Remote CIMOM” and list all subscribed indications, type the following at the interactive prompt: > c. pri nt_subscri bed _i nd i cati o ns() > To assign a list of these indications to a variable named i nd i cati o ns, type: > i nd i cati o ns = c. subscri bed _i nd i cati o ns() > Unsubscribing fro m Indicat io ns 358 Chapt er 1 9 . O penLMI By default, all subscriptions created by the LMIShell interpreter are automatically deleted when the interpreter terminates. To delete an individual subscription sooner, use the unsubscri be_i nd i cati o n() method as follows: connection_object.unsubscri be_i nd i cati o n(indication_name) Replace connection_object with the name of the connection object and indication_name with the name of the indication to delete. To delete all subscriptions, use the unsubscri be_al l _i nd i cati o ns() method: connection_object.unsubscri be_al l _i nd i cati o ns() Examp le 19 .39 . U n su b scrib in g f ro m In d icat io n s To use the c connection object created in Example 19.1, “ Connecting to a Remote CIMOM” and unsubscribe from the indication created in Example 19.37, “ Subscribing to Indications” , type the following at the interactive prompt: > c. unsubscri be_i nd i cati o n(' cpu' ) LMIReturnValue(rval=True, rparams=NocaseDict({}), errorstr='') > Im ple m e nt ing an Indicat io n Handle r The subscri be_i nd i cati o n() method allows you to specify the host name of the system you want to deliver the indications to. The following example shows how to implement an indication handler: > d ef hand l er(i nd , arg 1, arg 2, **kwarg s): ... expo rted _o bjects = i nd . expo rted _o bjects() ... d o _so methi ng _wi th(expo rted _o bjects) > l i stener = Lmi Ind i cati o nLi stener("0 . 0 . 0 . 0 ", l i steni ng _po rt) > l i stener. ad d _hand l er("i nd i cati o n-name-XXXXXXXX", hand l er, arg 1, arg 2, **kwarg s) > l i stener. start() > The first argument of the handler is an Lmi Ind i cati o n object, which contains a list of methods and objects exported by the indication. Other parameters are user specific: those arguments need to be specified when adding a handler to the listener. In the example above, the ad d _hand l er() method call uses a special string with eight “ X” characters. These characters are replaced with a random string that is generated by listeners in order to avoid a possible handler name collision. To use the random string, start the indication listener first and then subscribe to an indication so that the D esti nati o n property of the handler object contains the following value: schema: //host_name/random_string. Examp le 19 .4 0. Imp lemen t in g an In d icat io n H an d ler 359 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The following script illustrates how to write a handler that monitors a managed system located at 19 2. 16 8. 122. 1 and calls the i nd i cati o n_cal l back() function whenever a new user account is created: #!/usr/bin/lmishell import sys from time import sleep from lmi.shell.LMIUtil import LMIPassByRef from lmi.shell.LMIIndicationListener import LMIIndicationListener # These are passed by reference to indication_callback var1 = LMIPassByRef("some_value") var2 = LMIPassByRef("some_other_value") def indication_callback(ind, var1, var2): # Do something with ind, var1 and var2 print ind.exported_objects() print var1.value print var2.value c = connect("hostname", "username", "password") listener = LMIIndicationListener("0.0.0.0", 65500) unique_name = listener.add_handler( "demo-XXXXXXXX", # Creates a unique name for me indication_callback, # Callback to be called var1, # Variable passed by ref var2 # Variable passed by ref ) listener.start() print c.subscribe_indication( Name=unique_name, Query="SELECT * FROM LMI_AccountInstanceCreationIndication WHERE SOURCEINSTANCE ISA LMI_Account", Destination="192.168.122.1:65500" ) try: while True: sleep(60) except KeyboardInterrupt: sys.exit(0) 19.4 .10. Example Usage This section provides a number of examples for various CIM providers distributed with the OpenLMI packages. All examples in this section use the following two variable definitions: c = connect("host_name", "user_name", "password") ns = c.root.cimv2 360 Chapt er 1 9 . O penLMI Replace host_name with the host name of the managed system, user_name with the name of user that is allowed to connect to OpenPegasus CIMOM running on that system, and password with the user's password. Using t he Ope nLMI Se rvice Pro vide r The openlmi-service package installs a CIM provider for managing system services. The examples below illustrate how to use this CIM provider to list available system services and how to start, stop, enable, and disable them. Examp le 19 .4 1. List in g Availab le Services To list all available services on the managed machine along with information regarding whether the service has been started (T R UE) or stopped (FALSE) and the status string, use the following code snippet: for service in ns.LMI_Service.instances(): print "%s:\t%s" % (service.Name, service.Status) To list only the services that are enabled by default, use this code snippet: cls = ns.LMI_Service for service in cls.instances(): if service.EnabledDefault == cls.EnabledDefaultValues.Enabled: print service.Name Note that the value of the Enabl ed D efaul t property is equal to 2 for enabled services and 3 for disabled services. To display information about the cups service, use the following: cups = ns.LMI_Service.first_instance({"Name": "cups.service"}) cups.doc() Examp le 19 .4 2. St art in g an d St o p p in g Services To start and stop the cups service and to see its current status, use the following code snippet: cups = ns.LMI_Service.first_instance({"Name": "cups.service"}) cups.StartService() print cups.Status cups.StopService() print cups.Status Examp le 19 .4 3. En ab lin g an d D isab lin g Services To enable and disable the cups service and to display its Enabl ed D efaul t property, use the following code snippet: cups = ns.LMI_Service.first_instance({"Name": "cups.service"}) cups.TurnServiceOff() 361 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide print cups.EnabledDefault cups.TurnServiceOn() print cups.EnabledDefault Using t he Ope nLMI Ne t wo rking Pro vide r The openlmi-networking package installs a CIM provider for networking. The examples below illustrate how to use this CIM provider to list IP addresses associated with a certain port number, create a new connection, configure a static IP address, and activate a connection. Examp le 19 .4 4 . List in g IP Ad d resses Asso ciat ed wit h a G iven Po rt N u mb er To list all IP addresses associated with the eth0 network interface, use the following code snippet: device = ns.LMI_IPNetworkConnection.first_instance({'ElementName': 'eth0'}) for endpoint in device.associators(AssocClass="LMI_NetworkSAPSAPDependency", ResultClass="LMI_IPProtocolEndpoint"): if endpoint.ProtocolIFType == ns.LMI_IPProtocolEndpoint.ProtocolIFTypeValues.IPv4: print "IPv4: %s/%s" % (endpoint.IPv4Address, endpoint.SubnetMask) elif endpoint.ProtocolIFType == ns.LMI_IPProtocolEndpoint.ProtocolIFTypeValues.IPv6: print "IPv6: %s/%d" % (endpoint.IPv6Address, endpoint.IPv6SubnetPrefixLength) This code snippet uses the LMI_IP P ro to co l End po i nt class associated with a given LMI_IP Netwo rkC o nnecti o n class. To display the default gateway, use this code snippet: for rsap in device.associators(AssocClass="LMI_NetworkRemoteAccessAvailableToElement ", ResultClass="LMI_NetworkRemoteServiceAccessPoint"): if rsap.AccessContext == ns.LMI_NetworkRemoteServiceAccessPoint.AccessContextValues.DefaultGatew ay: print "Default Gateway: %s" % rsap.AccessInfo The default gateway is represented by an LMI_Netwo rkR emo teServi ceAccessP o i nt instance with the AccessC o ntext property equal to D efaul tG ateway. To get a list of D NS servers, the object model needs to be traversed as follows: 1. Get the LMI_IP P ro to co l End po i nt instances associated with a given LMI_IP Netwo rkC o nnecti o n using LMI_Netwo rkSAP SAP D epend ency. 2. Use the same association for the LMI_D NSP ro to co l End po i nt instances. 362 Chapt er 1 9 . O penLMI The LMI_Netwo rkR emo teServi ceAccessP o i nt instances with the AccessC o ntext property equal to the D NS Server associated through LMI_Netwo rkR emo teAccessAvai l abl eT o El ement have the D NS server address in the AccessInfo property. There can be more possible paths to get to the R emo teServi ceAccessP ath and entries can be duplicated. The following code snippet uses the set() function to remove duplicate entries from the list of D NS servers: dnsservers = set() for ipendpoint in device.associators(AssocClass="LMI_NetworkSAPSAPDependency", ResultClass="LMI_IPProtocolEndpoint"): for dnsedpoint in ipendpoint.associators(AssocClass="LMI_NetworkSAPSAPDependency", ResultClass="LMI_DNSProtocolEndpoint"): for rsap in dnsedpoint.associators(AssocClass="LMI_NetworkRemoteAccessAvailableToEle ment", ResultClass="LMI_NetworkRemoteServiceAccessPoint"): if rsap.AccessContext == ns.LMI_NetworkRemoteServiceAccessPoint.AccessContextValues.DNSServer: dnsservers.add(rsap.AccessInfo) print "DNS:", ", ".join(dnsservers) Examp le 19 .4 5. C reat in g a N ew C o n n ect io n an d C o n f ig u rin g a St at ic IP Ad d ress To create a new setting with a static IPv4 and stateless IPv6 configuration for network interface eth0, use the following code snippet: capability = ns.LMI_IPNetworkConnectionCapabilities.first_instance({ 'ElementName': 'eth0' }) result = capability.LMI_CreateIPSetting(Caption='eth0 Static', IPv4Type=capability.LMI_CreateIPSetting.IPv4TypeValues.Static, IPv6Type=capability.LMI_CreateIPSetting.IPv6TypeValues.Stateless) setting = result.rparams["SettingData"].to_instance() for settingData in setting.associators(AssocClass="LMI_OrderedIPAssignmentComponent"): if setting.ProtocolIFType == ns.LMI_IPAssignmentSettingData.ProtocolIFTypeValues.IPv4: # Set static IPv4 address settingData.IPAddresses = ["192.168.1.100"] settingData.SubnetMasks = ["255.255.0.0"] settingData.GatewayAddresses = ["192.168.1.1"] settingData.push() This code snippet creates a new setting by calling the LMI_C reateIP Setti ng () method on the instance of LMI_IP Netwo rkC o nnecti o nC apabi l i ti es, which is associated with LMI_IP Netwo rkC o nnecti o n through LMI_IP Netwo rkC o nnecti o nEl ementC apabi l i ti es. It also uses the push() method to modify the setting. Examp le 19 .4 6 . Act ivat in g a C o n n ect io n 363 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To apply a setting to the network interface, call the Appl ySetti ng T o IP Netwo rkC o nnecti o n() method of the LMI_IP C o nfi g urati o nServi ce class. This method is asynchronous and returns a job. The following code snippets illustrates how to call this method synchronously: setting = ns.LMI_IPAssignmentSettingData.first_instance({ "Caption": "eth0 Static" }) port = ns.LMI_IPNetworkConnection.first_instance({ 'ElementName': 'ens8' }) service = ns.LMI_IPConfigurationService.first_instance() service.SyncApplySettingToIPNetworkConnection(SettingData=setting, IPNetworkConnection=port, Mode=32768) The Mo d e parameter affects how the setting is applied. The most commonly used values of this parameter are as follows: 1 — apply the setting now and make it auto-activated. 2 — make the setting auto-activated and do not apply it now. 4 — disconnect and disable auto-activation. 5 — do not change the setting state, only disable auto-activation. 3276 8 — apply the setting. 3276 9 — disconnect. Using t he Ope nLMI St o rage Pro vide r The openlmi-storage package installs a CIM provider for storage management. The examples below illustrate how to use this CIM provider to create a volume group, create a logical volume, build a file system, mount a file system, and list block devices known to the system. In addition to the c and ns variables, these examples use the following variable definitions: MEGABYTE = 1024*1024 storage_service = ns.LMI_StorageConfigurationService.first_instance() filesystem_service = ns.LMI_FileSystemConfigurationService.first_instance() Examp le 19 .4 7. C reat in g a Vo lu me G ro u p To create a new volume group located in /d ev/myG ro up/ that has three members and the default extent size of 4 MB, use the following code snippet: # Find the devices to add to the volume group # (filtering the CIM_StorageExtent.instances() # call would be faster, but this is easier to read): sda1 = ns.CIM_StorageExtent.first_instance({"Name": "/dev/sda1"}) sdb1 = ns.CIM_StorageExtent.first_instance({"Name": "/dev/sdb1"}) sdc1 = ns.CIM_StorageExtent.first_instance({"Name": "/dev/sdc1"}) # Create a new volume group: (ret, outparams, err) = storage_service.SyncCreateOrModifyVG( ElementName="myGroup", 364 Chapt er 1 9 . O penLMI InExtents=[sda1, sdb1, sdc1]) vg = outparams['Pool'].to_instance() print "VG", vg.PoolID, \ "with extent size", vg.ExtentSize, \ "and", vg.RemainingExtents, "free extents created." Examp le 19 .4 8. C reat in g a Lo g ical Vo lu me To create two logical volumes with the size of 100 MB, use this code snippet: # Find the volume group: vg = ns.LMI_VGStoragePool.first_instance({"Name": "/dev/mapper/myGroup"}) # Create the first logical volume: (ret, outparams, err) = storage_service.SyncCreateOrModifyLV( ElementName="Vol1", InPool=vg, Size=100 * MEGABYTE) lv = outparams['TheElement'].to_instance() print "LV", lv.DeviceID, \ "with", lv.BlockSize * lv.NumberOfBlocks,\ "bytes created." # Create the second logical volume: (ret, outparams, err) = storage_service.SyncCreateOrModifyLV( ElementName="Vol2", InPool=vg, Size=100 * MEGABYTE) lv = outparams['TheElement'].to_instance() print "LV", lv.DeviceID, \ "with", lv.BlockSize * lv.NumberOfBlocks, \ "bytes created." Examp le 19 .4 9 . C reat in g a File Syst em To create an ext3 file system on logical volume l v from Example 19.48, “ Creating a Logical Volume” , use the following code snippet: (ret, outparams, err) = filesystem_service.SyncLMI_CreateFileSystem( FileSystemType=filesystem_service.LMI_CreateFileSystem.FileSystemTypeVa lues.EXT3, InExtents=[lv]) Examp le 19 .50. Mo u n t in g a File Syst em To mount the file system created in Example 19.49, “ Creating a File System” , use the following code snippet: # Find the file system on the logical volume: fs = lv.first_associator(ResultClass="LMI_LocalFileSystem") 365 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide mount_service = ns.LMI_MountConfigurationService.first_instance() (rc, out, err) = mount_service.SyncCreateMount( FileSystemType='ext3', Mode=32768, # just mount FileSystem=fs, MountPoint='/mnt/test', FileSystemSpec=lv.Name) Examp le 19 .51. List in g B lo ck D evices To list all block devices known to the system, use the following code snippet: devices = ns.CIM_StorageExtent.instances() for device in devices: if lmi_isinstance(device, ns.CIM_Memory): # Memory and CPU caches are StorageExtents too, do not print them continue print device.classname, print device.DeviceID, print device.Name, print device.BlockSize*device.NumberOfBlocks Using t he Ope nLMI Hardware Pro vide r The openlmi-hardware package installs a CIM provider for monitoring hardware. The examples below illustrate how to use this CIM provider to retrieve information about CPU, memory modules, PCI devices, and the manufacturer and model of the machine. Examp le 19 .52. Viewin g C PU In f o rmat io n To display basic CPU information such as the CPU name, the number of processor cores, and the number of hardware threads, use the following code snippet: cpu = ns.LMI_Processor.first_instance() cpu_cap = cpu.associators(ResultClass="LMI_ProcessorCapabilities")[0] print cpu.Name print cpu_cap.NumberOfProcessorCores print cpu_cap.NumberOfHardwareThreads Examp le 19 .53. Viewin g Memo ry In f o rmat io n To display basic information about memory modules such as their individual sizes, use the following code snippet: mem = ns.LMI_Memory.first_instance() for i in mem.associators(ResultClass="LMI_PhysicalMemory"): print i.Name 366 Chapt er 1 9 . O penLMI Examp le 19 .54 . Viewin g C h assis In f o rmat io n To display basic information about the machine such as its manufacturer or its model, use the following code snippet: chassis = ns.LMI_Chassis.first_instance() print chassis.Manufacturer print chassis.Model Examp le 19 .55. List in g PC I D evices To list all PCI devices known to the system, use the following code snippet: for pci in ns.LMI_PCIDevice.instances(): print pci.Name 19.5. Using OpenLMI Script s The LMIShell interpreter is built on top of Python modules that can be used to develop custom management tools. The OpenLMI Scripts project provides a number of Python libraries for interfacing with OpenLMI providers. In addition, it is distributed with l mi , an extensible utility that can be used to interact with these libraries from the command line. To install OpenLMI Scripts on your system, type the following at a shell prompt: easy_i nstal l --user o penl mi -scri pts This command installs the Python modules and the l mi utility in the ~ /. l o cal / directory. To extend the functionality of the l mi utility, install additional OpenLMI modules by using the following command: easy_i nstal l --user package_name For a complete list of available modules, see the Python website. For more information about OpenLMI Scripts, see the official OpenLMI Scripts documentation. 19.6. Addit ional Resources For more information about OpenLMI and system management in general, see the resources listed below. Inst alled Document at ion lmishell(1) — The manual page for the l mi shel l client and interpreter provides detailed information about its execution and usage. Online Document at ion 367 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Red Hat Enterprise Linux 7 Networking Guide — The Networking Guide for Red Hat Enterprise Linux 7 documents relevant information regarding the configuration and administration of network interfaces and network services on the system. Red Hat Enterprise Linux 7 Storage Administration Guide — The Storage Administration Guide for Red Hat Enterprise Linux 7 provides instructions on how to manage storage devices and file systems on the system. Red Hat Enterprise Linux 7 Power Management Guide — The Power Management Guide for Red Hat Enterprise Linux 7 explains how to manage power consumption of the system effectively. It discusses different techniques that lower power consumption for both servers and laptops, and explains how each technique affects the overall performance of the system. Red Hat Enterprise Linux 7 Linux D omain Identity, Authentication, and Policy Guide — The Linux Domain Identity, Authentication, and Policy Guide for Red Hat Enterprise Linux 7 covers all aspects of installing, configuring, and managing IPA domains, including both servers and clients. The guide is intended for IT and systems administrators. FreeIPA D ocumentation — The FreeIPA Documentation serves as the primary user documentation for using the FreeIPA Identity Management project. OpenSSL Home Page — The OpenSSL home page provides an overview of the OpenSSL project. Mozilla NSS D ocumentation — The Mozilla NSS Documentation serves as the primary user documentation for using the Mozilla NSS project. See Also Chapter 3, Managing Users and Groups documents how to manage system users and groups in the graphical user interface and on the command line. Chapter 7, Yum describes how to use the Yu m package manager to search, install, update, and uninstall packages on the command line. Chapter 8, Managing Services with systemd provides an introduction to systemd and documents how to use the systemctl command to manage system services, configure systemd targets, and execute power management commands. Chapter 9, OpenSSH describes how to configure an SSH server and how to use the ssh, scp, and sftp client utilities to access it. 368 Chapt er 2 0 . Viewing and Managing Log Files Chapter 20. Viewing and Managing Log Files Log files are files that contain messages about the system, including the kernel, services, and applications running on it. There are several types of log files for storing various information. For example, there is a default system log file, a log file just for security messages, and a log file for cron tasks. Log files can be very useful in many situations, for instance to troubleshoot a problem with the system, when trying to load a kernel driver, or when looking for unauthorized login attempts to the system. Some log files are controlled by a daemon called rsysl o g d . The rsysl o g d daemon is an enhanced replacement for sysklo g d , and provides extended filtering, various configuration options, input and output modules, support for transportation via the T C P or UD P protocols. A list of log files maintained by rsysl o g d can be found in the /etc/rsysl o g . co nf configuration file. Most log files are located in the /var/l o g / directory. Log files can also be managed by the jo urnal d daemon – a component of systemd . The jo urnal d daemon captures Syslog messages, kernel log messages, initial RAM disk and early boot messages as well as messages written to standard output and standard error output of all services, indexes them and makes this available to the user. The native journal file format, which is a structured and indexed binary file, improves searching and provides faster operation, and it also stores meta data information like time stamps or user ID s. Log files produced by jo urnal d are by default not persistent, log files are stored only in memory or a small ring-buffer in the /run/l o g /jo urnal / directory. The amount of logged data depends on free memory, when you reach the capacity limit, the oldest entries are deleted. However, this setting can be altered – see Section 20.9.5, “ Enabling Persistent Storage” . For more information on Journal see Section 20.9, “ Using the Journal” . By default, these two logging tools coexist on your system. The jo urnal d daemon is the primary tool for troubleshooting. It also provides additional data necessary for creating structured log messages. D ata acquired by jo urnal d is forwarded into the /run/systemd /jo urnal /sysl o g socket that may be used by rsysl o g d to process the data further. However, rsyslo g does the actual integration by default via the i mjo urnal input module, thus avoiding the aforementioned socket. You can also transfer data in the opposite direction, from rsysl o g d to jo urnal d with use of o mjo urnal module. See Section 20.6, “ Interaction of Rsyslog and Journal” for further information. The integration enables maintaining text-based logs in a consistent format to ensure compatibility with possible applications or configurations dependent on rsysl o g d . Also, you can maintain rsyslog messages in a structured format (see Section 20.7, “ Structured Logging with Rsyslog” ). 20.1. Locat ing Log Files Most log files are located in the /var/l o g / directory. Some applications such as httpd and samba have a directory within /var/l o g / for their log files. You may notice multiple files in the /var/l o g / directory with numbers after them (for example, cro n-20 10 0 9 0 6 ). These numbers represent a time stamp that has been added to a rotated log file. Log files are rotated so their file sizes do not become too large. The l o g ro tate package contains a cron task that automatically rotates log files according to the /etc/l o g ro tate. co nf configuration file and the configuration files in the /etc/l o g ro tate. d / directory. 20.2. Basic Configurat ion of Rsyslog 369 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The main configuration file for rsyslo g is /etc/rsysl o g . co nf. Here, you can specify global directives, modules, and rules that consist of filter and action parts. Also, you can add comments in the form of text following a hash sign (#). 20.2.1. Filt ers A rule is specified by a filter part, which selects a subset of syslog messages, and an action part, which specifies what to do with the selected messages. To define a rule in your /etc/rsysl o g . co nf configuration file, define both, a filter and an action, on one line and separate them with one or more spaces or tabs. rsyslo g offers various ways to filter syslog messages according to selected properties. The available filtering methods can be divided into Facility/Priority-based, Property-based, and Expressionbased filters. Facilit y/Prio rit y- b ased f ilt ers The most used and well-known way to filter syslog messages is to use the facility/prioritybased filters which filter syslog messages based on two conditions: facility and priority separated by a dot. To create a selector, use the following syntax: FACILITY.PRIORITY where: FACILITY specifies the subsystem that produces a specific syslog message. For example, the mai l subsystem handles all mail-related syslog messages. FACILITY can be represented by one of the following keywords (or by a numerical code): kern (0), user (1), mai l (2), d aemo n (3), auth (4), sysl o g (5), l pr (6), news (7), uucp (8), cro n (9), authpri v (10), ftp (11), and l o cal 0 through l o cal 7 (16 - 23). PRIORITY specifies a priority of a syslog message. PRIORITY can be represented by one of the following keywords (or by a number): d ebug (7), i nfo (6), no ti ce (5), warni ng (4), err (3), cri t (2), al ert (1), and emerg (0). The aforementioned syntax selects syslog messages with the defined or higher priority. By preceding any priority keyword with an equal sign (= ), you specify that only syslog messages with the specified priority will be selected. All other priorities will be ignored. Conversely, preceding a priority keyword with an exclamation mark (! ) selects all syslog messages except those with the defined priority. In addition to the keywords specified above, you may also use an asterisk (*) to define all facilities or priorities (depending on where you place the asterisk, before or after the comma). Specifying the priority keyword no ne serves for facilities with no given priorities. Both facility and priority conditions are case-insensitive. To define multiple facilities and priorities, separate them with a comma (,). To define multiple selectors on one line, separate them with a semi-colon (;). Note that each selector in the selector field is capable of overwriting the preceding ones, which can exclude some priorities from the pattern. Examp le 20.1. Facilit y/Prio rit y- b ased Filt ers The following are a few examples of simple facility/priority-based filters that can be specified in /etc/rsysl o g . co nf. To select all kernel syslog messages with any priority, add the following text into the configuration file: 370 Chapt er 2 0 . Viewing and Managing Log Files kern.* To select all mail syslog messages with priority cri t and higher, use this form: mail.crit To select all cron syslog messages except those with the i nfo or d ebug priority, set the configuration in the following form: cron.!info,!debug Pro p ert y- b ased f ilt ers Property-based filters let you filter syslog messages by any property, such as timegenerated or syslogtag. For more information on properties, see Section 20.2.3, “ Properties” . You can compare each of the specified properties to a particular value using one of the compare-operations listed in Table 20.1, “ Property-based compare-operations” . Both property names and compare operations are case-sensitive. Property-based filter must start with a colon (: ). To define the filter, use the following syntax: :PROPERTY, [!]COMPARE_OPERATION, "STRING" where: The PROPERTY attribute specifies the desired property. The optional exclamation point (! ) negates the output of the compare-operation. Other Boolean operators are currently not supported in property-based filters. The COMPARE_OPERATION attribute specifies one of the compare-operations listed in Table 20.1, “ Property-based compare-operations” . The STRING attribute specifies the value that the text provided by the property is compared to. This value must be enclosed in quotation marks. To escape certain character inside the string (for example a quotation mark (")), use the backslash character (\). T ab le 20.1. Pro p ert y- b ased co mp are- o p erat io n s C o mp are- o p erat io n D escrip t io n contains Checks whether the provided string matches any part of the text provided by the property. To perform caseinsensitive comparisons, use contains_i. Compares the provided string against all of the text provided by the property. These two values must be exactly equal to match. Checks whether the provided string is found exactly at the beginning of the text provided by the property. To perform case-insensitive comparisons, use startswith_i. Compares the provided POSIX BRE (Basic Regular Expression) against the text provided by the property. isequal startswith regex 371 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide C o mp are- o p erat io n D escrip t io n ereregex Compares the provided POSIX ERE (Extended Regular Expression) regular expression against the text provided by the property. Checks if the property is empty. The value is discarded. This is especially useful when working with normalized data, where some fields may be populated based on normalization result. isempty Examp le 20.2. Pro p ert y- b ased Filt ers The following are a few examples of property-based filters that can be specified in /etc/rsysl o g . co nf. To select syslog messages which contain the string erro r in their message text, use: :msg, contains, "error" The following filter selects syslog messages received from the host name ho st1: :hostname, isequal, "host1" To select syslog messages which do not contain any mention of the words fatal and erro r with any or no text between them (for example, fatal l i b erro r), type: :msg, !regex, "fatal .* error" Exp ressio n - b ased f ilt ers Expression-based filters select syslog messages according to defined arithmetic, Boolean or string operations. Expression-based filters use rsyslo g 's own scripting language called RainerScript to build complex filters. See Section 20.11, “ Online D ocumentation” for the syntax definition of this script along with examples of various expression-based filters. Also RainerScript is a basis for rsyslo g 's new configuration format, see Section 20.2.6, “ Using the New Configuration Format” The basic syntax of expression-based filter looks as follows: if EXPRESSION then ACTION else ACTION where: The EXPRESSION attribute represents an expression to be evaluated, for example: $msg startswi th ' D EVNAME' or $sysl o g faci l i ty-text = = ' l o cal 0 ' . You can specify more than one expression in a single filter by using and and o r operators. The ACTION attribute represents an action to be performed if the expression returns the value true. This can be a single action, or an arbitrary complex script enclosed in curly braces. Expression-based filters are indicated by the keyword if at the start of a new line. The then keyword separates the EXPRESSION from the ACTION. Optionally, you can employ the else keyword to specify what action is to be performed in case the condition is not met. With expression-based filters, you can nest the conditions by using a script enclosed in 372 Chapt er 2 0 . Viewing and Managing Log Files curly braces as in Example 20.3, “ Expression-based Filters” . The script allows you to use facility/priority-based filters inside the expression. On the other hand, property-based filters are not recommended here. RainerScript supports regular expressions with specialized functions re_match() and re_extract(). Examp le 20.3. Exp ressio n - b ased Filt ers The following expression contains two nested conditions. The log files created by a program called prog1 are split into two files based on the presence of the " test" string in the message. if $programname == 'prog1' then { action(type="omfile" file="/var/log/prog1.log") if $msg contains 'test' then action(type="omfile" file="/var/log/prog1test.log") else action(type="omfile" file="/var/log/prog1notest.log") } 20.2.2. Act ions Actions specify what is to be done with the messages filtered out by an already-defined selector. The following are some of the actions you can define in your rule: Savin g syslo g messag es t o lo g f iles The majority of actions specify to which log file a syslog message is saved. This is done by specifying a file path after your already-defined selector: FILTER PATH where FILTER stands for user-specified selector and PATH is a path of a target file. For instance, the following rule is comprised of a selector that selects all cro n syslog messages and an action that saves them into the /var/l o g /cro n. l o g log file: cron.* /var/log/cron.log By default, the log file is synchronized every time a syslog message is generated. Use a dash mark (-) as a prefix of the file path you specified to omit syncing: FILTER -PATH Note that you might lose information if the system terminates right after a write attempt. However, this setting can improve performance, especially if you run programs that produce very verbose log messages. Your specified file path can be either static or dynamic. Static files are represented by a fixed file path as shown in the example above. D ynamic file paths can differ according to the received message. D ynamic file paths are represented by a template and a question mark (?) prefix: FILTER ?DynamicFile 373 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide where DynamicFile is a name of a predefined template that modifies output paths. You can use the dash prefix (-) to disable syncing, also you can use multiple templates separated by a colon (;). For more information on templates, see Section 20.2.3, “ Generating D ynamic File Names” . If the file you specified is an existing t ermin al or /d ev/co nso l e device, syslog messages are sent to standard output (using special t ermin al-handling) or your console (using special /d ev/co nso l e-handling) when using the X Window System, respectively. Sen d in g syslo g messag es o ver t h e n et wo rk rsyslo g allows you to send and receive syslog messages over the network. This feature allows you to administer syslog messages of multiple hosts on one machine. To forward syslog messages to a remote machine, use the following syntax: @ [(zNUMBER)]HOST:[PORT] where: The at sign (@ ) indicates that the syslog messages are forwarded to a host using the UD P protocol. To use the T C P protocol, use two at signs with no space between them (@ @ ). The optional zNUMBER setting enables z lib compression for syslog messages. The NUMBER attribute specifies the level of compression (from 1 – lowest to 9 – maximum). Compression gain is automatically checked by rsysl o g d , messages are compressed only if there is any compression gain and messages below 60 bytes are never compressed. The HOST attribute specifies the host which receives the selected syslog messages. The PORT attribute specifies the host machine's port. When specifying an IP v6 address as the host, enclose the address in square brackets ([, ]). Examp le 20.4 . Sen d in g syslo g Messag es o ver t h e N et wo rk The following are some examples of actions that forward syslog messages over the network (note that all actions are preceded with a selector that selects all messages with any priority). To forward messages to 19 2. 16 8. 0 . 1 via the UD P protocol, type: *.* @ 192.168.0.1 To forward messages to " example.com" using port 18 and the T C P protocol, use: *.* @ @ example.com:18 The following compresses messages with z lib (level 9 compression) and forwards them to 20 0 1: d b8: : 1 using the UD P protocol *.* @ (z9)[2001:db8::1] O u t p u t ch an n els 374 Chapt er 2 0 . Viewing and Managing Log Files Output channels are primarily used to specify the maximum size a log file can grow to. This is very useful for log file rotation (for more information see Section 20.2.5, “ Log Rotation” ). An output channel is basically a collection of information about the output action. Output channels are defined by the $o utchannel directive. To define an output channel in /etc/rsysl o g . co nf, use the following syntax: $outchannel NAME, FILE_NAME, MAX_SIZE, ACTION where: The NAME attribute specifies the name of the output channel. The FILE_NAME attribute specifies the name of the output file. Output channels can write only into files, not pipes, terminal, or other kind of output. The MAX_SIZE attribute represents the maximum size the specified file (in FILE_NAME) can grow to. This value is specified in bytes. The ACTION attribute specifies the action that is taken when the maximum size, defined in MAX_SIZE, is hit. To use the defined output channel as an action inside a rule, type: FILTER :omfile:$NAME Examp le 20.5. O u t p u t ch an n el lo g ro t at io n The following output shows a simple log rotation through the use of an output channel. First, the output channel is defined via the $outchannel directive: $outchannel log_rotation, /var/log/test_log.log, 104857600, /home/joe/log_rotation_script and then it is used in a rule that selects every syslog message with any priority and executes the previously-defined output channel on the acquired syslog messages: *.* :omfile:$log_rotation Once the limit (in the example 10 0 MB) is hit, the /ho me/jo e/l o g _ro tati o n_scri pt is executed. This script can contain anything from moving the file into a different folder, editing specific content out of it, or simply removing it. Sen d in g syslo g messag es t o sp ecif ic u sers rsyslo g can send syslog messages to specific users by specifying a user name of the user you want to send the messages to (as in Example 20.7, “ Specifying Multiple Actions” ). To specify more than one user, separate each user name with a comma (,). To send messages to every user that is currently logged on, use an asterisk (*). Execu t in g a p ro g ram rsyslo g lets you execute a program for selected syslog messages and uses the system() call to execute the program in shell. To specify a program to be executed, prefix it with a caret character (^). Consequently, specify a template that formats the received message and passes it to the specified executable as a one line parameter (for more information on 375 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide templates, see Section 20.2.3, “ Templates” ). FILTER ^EXECUTABLE; TEMPLATE Here an output of the FILTER condition is processed by a program represented by EXECUTABLE. This program can be any valid executable. Replace TEMPLATE with the name of the formatting template. Examp le 20.6 . Execu t in g a Pro g ram In the following example, any syslog message with any priority is selected, formatted with the template template and passed as a parameter to the t est - p ro g ram program, which is then executed with the provided parameter: *.* ^test-program;template Be careful when using the shell execute action When accepting messages from any host, and using the shell execute action, you may be vulnerable to command injection. An attacker may try to inject and execute commands in the program you specified to be executed in your action. To avoid any possible security threats, thoroughly consider the use of the shell execute action. St o rin g syslo g messag es in a d at ab ase Selected syslog messages can be directly written into a database table using the database writer action. The database writer uses the following syntax: :PLUGIN:DB_HOST,DB_NAME,DB_USER,DB_PASSWORD;[TEMPLATE] where: The PLUGIN calls the specified plug-in that handles the database writing (for example, the o mmysq l plug-in). The DB_HOST attribute specifies the database host name. The DB_NAME attribute specifies the name of the database. The DB_USER attribute specifies the database user. The DB_PASSWORD attribute specifies the password used with the aforementioned database user. The TEMPLATE attribute specifies an optional use of a template that modifies the syslog message. For more information on templates, see Section 20.2.3, “ Templates” . 376 Chapt er 2 0 . Viewing and Managing Log Files Using MySQL and PostgreSQL Currently, rsyslo g provides support for MySQ L and P o stg reSQ L databases only. In order to use the MySQ L and P o stg reSQ L database writer functionality, install the rsyslog-mysql and rsyslog-pgsql packages, respectively. Also, make sure you load the appropriate modules in your /etc/rsysl o g . co nf configuration file: $ModLoad ommysql $ModLoad ompgsql # Output module for MySQL support # Output module for PostgreSQL support For more information on rsyslo g modules, see Section 20.5, “ Using Rsyslog Modules” . Alternatively, you may use a generic database interface provided by the o ml i bd b module (supports: Firebird/Interbase, MS SQL, Sybase, SQLLite, Ingres, Oracle, mSQL). D iscard in g syslo g messag es To discard your selected messages, use the tilde character (~ ). FILTER ~ The discard action is mostly used to filter out messages before carrying on any further processing. It can be effective if you want to omit some repeating messages that would otherwise fill the log files. The results of discard action depend on where in the configuration file it is specified, for the best results place these actions on top of the actions list. Please note that once a message has been discarded there is no way to retrieve it in later configuration file lines. For instance, the following rule discards any cron syslog messages: cron.* ~ Spe cifying Mult iple Act io ns For each selector, you are allowed to specify multiple actions. To specify multiple actions for one selector, write each action on a separate line and precede it with an ampersand (&) character: FILTER ACTION & ACTION & ACTION Specifying multiple actions improves the overall performance of the desired outcome since the specified selector has to be evaluated only once. Examp le 20.7. Sp ecif yin g Mu lt ip le Act io n s In the following example, all kernel syslog messages with the critical priority (crit) are sent to user user1, processed by the template temp and passed on to the test-program executable, and forwarded to 19 2. 16 8. 0 . 1 via the UD P protocol. 377 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide kern.=crit user1 & ^test-program;temp & @ 192.168.0.1 Any action can be followed by a template that formats the message. To specify a template, suffix an action with a semicolon (;) and specify the name of the template. For more information on templates, see Section 20.2.3, “ Templates” . Using templates A template must be defined before it is used in an action, otherwise it is ignored. In other words, template definitions should always precede rule definitions in /etc/rsysl o g . co nf. 20.2.3. T emplat es Any output that is generated by rsyslo g can be modified and formatted according to your needs with the use of templates. To create a template use the following syntax in /etc/rsysl o g . co nf: $template TEMPLATE_NAME,"text %PROPERTY% more text", [OPTION] where: $template is the template directive that indicates that the text following it, defines a template. TEMPLATE_NAME is the name of the template. Use this name to refer to the template. Anything between the two quotation marks ("…") is the actual template text. Within this text, special characters, such as \n for new line or \r for carriage return, can be used. Other characters, such as % or ", have to be escaped if you want to use those characters literally. The text specified between two percent signs (%) specifies a property that allows you to access specific contents of a syslog message. For more information on properties, see Section 20.2.3, “ Properties” . The OPTION attribute specifies any options that modify the template functionality. The currently supported template options are sql and stdsql, which are used for formatting the text as an SQL query. Note Note that the database writer checks whether the sql or stdsql options are specified in the template. If they are not, the database writer does not perform any action. This is to prevent any possible security threats, such as SQL injection. See section Storing syslog messages in a database in Section 20.2.2, “ Actions” for more information. Ge ne rat ing Dynam ic File Nam e s Templates can be used to generate dynamic file names. By specifying a property as a part of the file 378 Chapt er 2 0 . Viewing and Managing Log Files path, a new file will be created for each unique property, which is a convenient way to classify syslog messages. For example, use the timegenerated property, which extracts a time stamp from the message, to generate a unique file name for each syslog message: $template DynamicFile,"/var/log/test_logs/%timegenerated%-test.log" Keep in mind that the $template directive only specifies the template. You must use it inside a rule for it to take effect. In /etc/rsysl o g . co nf, use the question mark (?) in an action definition to mark the dynamic file name template: *.* ?DynamicFile Pro pe rt ie s Properties defined inside a template (between two percent signs (%)) enable access various contents of a syslog message through the use of a property replacer. To define a property inside a template (between the two quotation marks ("…")), use the following syntax: %PROPERTY_NAME[:FROM_CHAR:TO_CHAR:OPTION]% where: The PROPERTY_NAME attribute specifies the name of a property. A list of all available properties and their detailed description can be found in the rsysl o g . co nf(5) manual page under the section Available Properties. FROM_CHAR and TO_CHAR attributes denote a range of characters that the specified property will act upon. Alternatively, regular expressions can be used to specify a range of characters. To do so, set the letter R as the FROM_CHAR attribute and specify your desired regular expression as the TO_CHAR attribute. The OPTION attribute specifies any property options, such as the l o wercase option to convert the input to lowercase. A list of all available property options and their detailed description can be found in the rsysl o g . co nf(5) manual page under the section Property Options. The following are some examples of simple properties: The following property obtains the whole message text of a syslog message: %msg% The following property obtains the first two characters of the message text of a syslog message: %msg:1:2% The following property obtains the whole message text of a syslog message and drops its last line feed character: %msg:::drop-last-lf% The following property obtains the first 10 characters of the time stamp that is generated when the syslog message is received and formats it according to the RFC 3999 date standard. 379 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide %timegenerated:1:10:date-rfc3339% T e m plat e Exam ple s This section presents a few examples of rsyslo g templates. Example 20.8, “ A verbose syslog message template” shows a template that formats a syslog message so that it outputs the message's severity, facility, the time stamp of when the message was received, the host name, the message tag, the message text, and ends with a new line. Examp le 20.8. A verb o se syslo g messag e t emp lat e $template verbose, "%syslogseverity%, %syslogfacility%, %timegenerated%, %HOSTNAME%, %syslogtag%, %msg%\n" Example 20.9, “ A wall message template” shows a template that resembles a traditional wall message (a message that is send to every user that is logged in and has their mesg(1) permission set to yes). This template outputs the message text, along with a host name, message tag and a time stamp, on a new line (using \r and \n) and rings the bell (using \7). Examp le 20.9 . A wall messag e t emp lat e $template wallmsg,"\r\n\7Message from syslogd@ %HOSTNAME% at %timegenerated% ...\r\n %syslogtag% %msg%\n\r" Example 20.10, “ A database formatted message template” shows a template that formats a syslog message so that it can be used as a database query. Notice the use of the sql option at the end of the template specified as the template option. It tells the database writer to format the message as an MySQL SQ L query. Examp le 20.10. A d at ab ase f o rmat t ed messag e t emp lat e $template dbFormat,"insert into SystemEvents (Message, Facility, FromHost, Priority, DeviceReportedTime, ReceivedAt, InfoUnitID, SysLogTag) values ('%msg%', %syslogfacility%, '%HOSTNAME%', %syslogpriority%, '%timereported:::date-mysql%', '%timegenerated:::date-mysql%', %iut%, '%syslogtag%')", sql rsyslo g also contains a set of predefined templates identified by the R SY SLO G _ prefix. These are reserved for the syslog's use and it is advisable to not create a template using this prefix to avoid conflicts. The following list shows these predefined templates along with their definitions. RSYSLOG_DebugFormat A special format used for troubleshooting property problems. "Debug line with all properties:\nFROMHOST: '%FROMHOST%', fromhost-ip: '%fromhost-ip%', HOSTNAME: '%HOSTNAME%', PRI: %PRI%,\nsyslogtag '%syslogtag%', programname: '%programname%', 380 Chapt er 2 0 . Viewing and Managing Log Files APP-NAME: '%APP-NAME%', PROCID: '%PROCID%', MSGID: '%MSGID%',\nTIMESTAMP: '%TIMESTAMP%', STRUCTURED-DATA: '%STRUCTURED-DATA%',\nmsg: '%msg%'\nescaped msg: '%msg:::dropcc%'\nrawmsg: '%rawmsg%'\n\n\" RSYSLOG_SyslogProtocol23Format The format specified in IETF's internet-draft ietf-syslog-protocol-23, which is assumed to become the new syslog standard RFC. "%PRI%1 %TIMESTAMP:::date-rfc3339% %HOSTNAME% %APP-NAME% %PROCID% %MSGID% %STRUCTURED-DATA% %msg%\n\" RSYSLOG_FileFormat A modern-style logfile format similar to TraditionalFileFormat, but with high-precision time stamps and time zone information. "%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag%%msg:::sp-if-no1st-sp%%msg:::drop-last-lf%\n\" RSYSLOG_TraditionalFileFormat The older default log file format with low-precision time stamps. "%TIMESTAMP% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1stsp%%msg:::drop-last-lf%\n\" RSYSLOG_ForwardFormat A forwarding format with high-precision time stamps and time zone information. "%PRI%%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag:1:32%%msg:::sp-if-no-1st-sp%%msg%\" RSYSLOG_TraditionalForwardFormat The traditional forwarding format with low-precision time stamps. "%PRI%%TIMESTAMP% %HOSTNAME% %syslogtag:1:32%%msg:::sp-if-no-1stsp%%msg%\" 20.2.4 . Global Direct ives Global directives are configuration options that apply to the rsysl o g d daemon. They usually specify a value for a specific predefined variable that affects the behavior of the rsysl o g d daemon or a rule that follows. All of the global directives must start with a dollar sign ($). Only one directive can be specified per line. The following is an example of a global directive that specifies the maximum size of the syslog message queue: $MainMsgQueueSize 50000 The default size defined for this directive (10 ,0 0 0 messages) can be overridden by specifying a different value (as shown in the example above). 381 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide You may define multiple directives in your /etc/rsysl o g . co nf configuration file. A directive affects the behavior of all configuration options until another occurrence of that same directive is detected. Global directives can be used to configure actions, queues and for debugging. A comprehensive list of all available configuration directives can be found in Section 20.11, “ Online D ocumentation” . Currently, a new configuration format has been developed that replaces the $based syntax (see Section 20.2.6, “ Using the New Configuration Format” ). However, classic global directives remain supported as a legacy format. 20.2.5. Log Rot at ion The following is a sample /etc/l o g ro tate. co nf configuration file: # rotate log files weekly weekly # keep 4 weeks worth of backlogs rotate 4 # uncomment this if you want your log files compressed compress All of the lines in the sample configuration file define global options that apply to every log file. In our example, log files are rotated weekly, rotated log files are kept for four weeks, and all rotated log files are compressed by g z ip into the . g z format. Any lines that begin with a hash sign (#) are comments and are not processed. You may define configuration options for a specific log file and place it under the global options. However, it is advisable to create a separate configuration file for any specific log file in the /etc/l o g ro tate. d / directory and define any configuration options there. The following is an example of a configuration file placed in the /etc/l o g ro tate. d / directory: /var/log/messages { rotate 5 weekly postrotate /usr/bin/killall -HUP syslogd endscript } The configuration options in this file are specific for the /var/l o g /messag es log file only. The settings specified here override the global settings where possible. Thus the rotated /var/l o g /messag es log file will be kept for five weeks instead of four weeks as was defined in the global options. The following is a list of some of the directives you can specify in your lo g ro t at e configuration file: weekly — Specifies the rotation of log files to be done weekly. Similar directives include: daily monthly yearly compress — Enables compression of rotated log files. Similar directives include: nocompress 382 Chapt er 2 0 . Viewing and Managing Log Files compresscmd — Specifies the command to be used for compressing. uncompresscmd compressext — Specifies what extension is to be used for compressing. compressoptions — Lets you specify any options that may be passed to the used compression program. delaycompress — Postpones the compression of log files to the next rotation of log files. rotate INTEGER — Specifies the number of rotations a log file undergoes before it is removed or mailed to a specific address. If the value 0 is specified, old log files are removed instead of rotated. mail ADDRESS — This option enables mailing of log files that have been rotated as many times as is defined by the rotate directive to the specified address. Similar directives include: nomail mailfirst — Specifies that the just-rotated log files are to be mailed, instead of the about-toexpire log files. maillast — Specifies that the about-to-expire log files are to be mailed, instead of the justrotated log files. This is the default option when mail is enabled. For the full list of directives and various configuration options, see the l o g ro tate(5) manual page. 20.2.6. Using t he New Configurat ion Format In rsyslo g version 7, installed by default for Red Hat Enterprise Linux 7 in the rsyslog package, a new configuration syntax is introduced. This new configuration format aims to be more powerful, more intuitive, and to prevent common mistakes by not permitting certain invalid constructs. The syntax enhancement is enabled by the new configuration processor that relies on RainerScript. The legacy format is still fully supported and it is used by default in the /etc/rsysl o g . co nf configuration file. RainerScript is a scripting language designed for processing network events and configuring event processors such as rsyslo g . RainerScript was primarily used to define expression-based filters, see Example 20.3, “ Expression-based Filters” . The newest version of RainerScript implements the i nput() and rul eset() statements, which permit the /etc/rsysl o g . co nf configuration file to be written in the new style only. In the following examples you can compare the configuration written with legacy-style parameters: $InputFileName /tmp/inputfile $InputFileTag tag1: $InputFileStateFile inputfile-state $InputRunFileMonitor and the same configuration with use of the new format statement: input(type="imfile" file="/tmp/inputfile" tag="tag1:" statefile="inputfile-state") This significantly reduces the number of parameters used in configuration, improves readability, and also provides higher execution speed. For more information on RainerScript statements and parameters see Section 20.11, “ Online D ocumentation” . 383 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 20.2.7. Ruleset s Leaving special directives aside, rsyslo g handles messages as defined by rules that consist of a filter condition and an action to be performed if the condition is true. With a traditionally written /etc/rsysl o g . co nf file, all rules are evaluated in order of appearance for every input message. This process starts with the first rule and continues until all rules have been processed or until the message is discarded by one of the rules. However, rules can be grouped into sequences called rulesets. With rulesets, you can limit the effect of certain rules only to selected inputs or enhance the performance of rsyslo g by defining a distinct set of actions bound to a specific input. In other words, filter conditions that will be inevitably evaluated as false for certain types of messages can be skipped. With the new configuration format, the i nput() and rul eset() statements are reserved for this operation. The ruleset definition in /etc/rsysl o g . co nf can look as follows: ruleset(name="rulesetname") { rule rule2 call rulesetname2 … } Replace rulesetname with an identifier for your ruleset. The ruleset name cannot start with R SY SLO G _ since this namespace is reserved for use by rsyslo g . R SY SLO G _D efaul tR ul eset then defines the default set of rules to be performed if the message has no other ruleset assigned. With rule and rule2 you can define rules in filter-action format mentioned above. With the call parameter, you can nest rulesets by calling them from inside other ruleset blocks. After creating a ruleset, you need to specify what input it will apply to: input(type="input_type" port="port_num" ruleset="rulesetname"); Here you can identify an input message by input_type, which is an input module that gathered the message, or by port_num – the port number. Other parameters such as file or tag can be specified for i nput(). Replace rulesetname with a name of the ruleset to be evaluated against the message. In case an input message is not explicitly bound to a ruleset, the default ruleset is triggered. You can also use the legacy format to define rulesets, for more information see Section 20.11, “ Online D ocumentation” . Examp le 20.11. U sin g ru leset s The following rulesets ensure different handling of remote messages coming from different ports. Add the following into /etc/rsysl o g . co nf: ruleset(name="remote-10514") { action(type="omfile" file="/var/log/remote-10514") } ruleset(name="remote-10515") { cron.* action(type="omfile" file="/var/log/remote-10515-cron") mail.* action(type="omfile" file="/var/log/remote-10515-mail") 384 Chapt er 2 0 . Viewing and Managing Log Files } input(type="imtcp" port="10514" ruleset="remote-10514"); input(type="imtcp" port="10515" ruleset="remote-10515"); Rulesets shown in the above example define log destinations for the remote input from two ports, in case of 10515, messages are sorted according to the facility. Then, the TCP input is enabled and bound to rulesets. Note that you must load the required modules (imtcp) for this configuration to work. 20.2.8. Compat ibilit y wit h syslogd From rsyslo g version 6, compatibility mode specified via the -c option has been removed. Also, the syslogd-style command-line options are deprecated and configuring rsyslo g through these command-line options should be avoided. However, you can use several templates and directives to configure rsysl o g d to emulate syslogd-like behavior. For more information on various rsysl o g d options, see the rsysl o g d (8)manual page. 20.3. Working wit h Queues in Rsyslog Queues are used to pass content, mostly syslog messages, between components of rsyslo g . With queues, rsyslog is capable of processing multiple messages simultaneously and to apply several actions to a single message at once. The data flow inside rsyslo g can be illustrated as follows: Fig u re 20.1. Messag e Flo w in R syslo g Whenever rsyslo g receives a message, it passes this message to the preprocessor and then places it into the main message queue. Messages wait there to be dequeued and passed to the rule processor. The rule processor is a parsing and filtering engine. Here, the rules defined in /etc/rsysl o g . co nf 385 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide are applied. Based on these rules, the rule processor evaluates which actions are to be performed. Each action has its own action queue. Messages are passed through this queue to the respective action processor which creates the final output. Note that at this point, several actions can run simultaneously on one message. For this purpose, a message is duplicated and passed to multiple action processors. Only one queue per action is possible. D epending on configuration, the messages can be sent right to the action processor without action queuing. This is the behavior of direct queues (see below). In case the output action fails, the action processor notifies the action queue, which then takes an unprocessed element back and after some time interval, the action is attempted again. To sum up, there are two positions where queues stand in rsyslo g : either in front of the rule processor as a single main message queue or in front of various types of output actions as action queues. Queues provide two main advantages that both lead to increased performance of message processing: they serve as buffers that decouple producers and consumers in the structure of rsyslo g they allow for parallelization of actions performed on messages Apart from this, queues can be configured with several directives to provide optimal performance for your system. These configuration options are covered in the following sections. Warning If an output plug-in is unable to deliver a message, it is stored in the preceding message queue. If the queue fills, the inputs block until it is no longer full. This will prevent new messages from being logged via the blocked queue. In the absence of separate action queues this can have severe consequences, such as preventing SSH logging, which in turn can prevent SSH access. Therefore it is advised to use dedicated action queues for outputs which are forwarded over a network or to a database. 20.3.1. Defining Queues Based on where the messages are stored, there are several types of queues: direct, in-memory, disk, and disk-assisted in-memory queues that are most widely used. You can choose one of these types for the main message queue and also for action queues. Add the following into /etc/rsysl o g . co nf: $objectQueueType queue_type Here, you can apply the setting for the main message queue (replace object with Mai nMsg ) or for an action queue (replace object with Acti o n). Replace queue_type with one of d i rect, l i nked l i st or fi xed array (which are in-memory queues), or d i sk. The default setting for a main message queue is the FixedArray queue with a limit of 10,000 messages. Action queues are by default set as D irect queues. Dire ct Que ue s For many simple operations, such as when writing output to a local file, building a queue in front of an action is not needed. To avoid queuing, use: $objectQueueType Direct 386 Chapt er 2 0 . Viewing and Managing Log Files Replace object with Mai nMsg or with Acti o n to use this option to the main message queue or for an action queue respectively. With direct queue, messages are passed directly and immediately from the producer to the consumer. Disk Que ue s D isk queues store messages strictly on a hard drive, which makes them highly reliable but also the slowest of all possible queuing modes. This mode can be used to prevent the loss of highly important log data. However, disk queues are not recommended in most use cases. To set a disk queue, type the following into /etc/rsysl o g . co nf: $objectQueueType Disk Replace object with Mai nMsg or with Acti o n to use this option to the main message queue or for an action queue respectively. D isk queues are written in parts, with a default size 10 Mb. This default size can be modified with the following configuration directive: $objectQueueMaxFileSize size where size represents the specified size of disk queue part. The defined size limit is not restrictive, rsyslo g always writes one complete queue entry, even if it violates the size limit. Each part of a disk queue matches with an individual file. The naming directive for these files looks as follows: $objectQueueFilename name This sets a name prefix for the file followed by a 7-digit number starting at one and incremented for each file. In-m e m o ry Que ue s With in-memory queue, the enqueued messages are held in memory which makes the process very fast. The queued data is lost if the computer is power cycled or shut down. However, you can use the $Acti o nQ ueueSaveO nShutd o wn setting to save the data before shutdown. There are two types of in-memory queues: FixedArray queue — the default mode for the main message queue, with a limit of 10,000 elements. This type of queue uses a fixed, pre-allocated array that holds pointers to queue elements. D ue to these pointers, even if the queue is empty a certain amount of memory is consumed. However, FixedArray offers the best run time performance and is optimal when you expect a relatively low number of queued messages and high performance. LinkedList queue — here, all structures are dynamically allocated in a linked list, thus the memory is allocated only when needed. LinkedList queues handle occasional message bursts very well. In general, use LinkedList queues when in doubt. Compared to FixedArray, it consumes less memory and lowers the processing overhead. Use the following syntax to configure in-memory queues: $objectQueueType LinkedList $objectQueueType FixedArray 387 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Replace object with Mai nMsg or with Acti o n to use this option to the main message queue or for an action queue respectively. Disk-Assist e d In-m e m o ry Que ue s Both disk and in-memory queues have their advantages and rsyslo g lets you combine them in diskassisted in-memory queues. To do so, configure a normal in-memory queue and then add the $o bjectQ ueueFi l eName directive to define a file name for disk assistance. This queue then becomes disk-assisted, which means it couples an in-memory queue with a disk queue to work in tandem. The disk queue is activated if the in-memory queue is full or needs to persist after shutdown. With a disk-assisted queue, you can set both disk-specific and in-memory specific configuration parameters. This type of queue is probably the most commonly used, it is especially useful for potentially long-running and unreliable actions. To specify the functioning of a disk-assisted in-memory queue, use the so-called watermarks: $objectQueueHighWatermark number $objectQueueLowWatermark number Replace object with Mai nMsg or with Acti o n to use this option to the main message queue or for an action queue respectively. Replace number with a number of enqueued messages. When an inmemory queue reaches the number defined by the high watermark, it starts writing messages to disk and continues until the in-memory queue size drops to the number defined with the low watermark. Correctly set watermarks minimize unnecessary disk writes, but also leave memory space for message bursts since writing to disk files is rather lengthy. Therefore, the high watermark must be lower than the whole queue capacity set with $objectQueueSize. The difference between the high watermark and the overall queue size is a spare memory buffer reserved for message bursts. On the other hand, setting the high watermark too low will turn on disk assistance unnecessarily often. Examp le 20.12. R eliab le Fo rward in g o f Lo g Messag es t o a Server Rsyslog is often used to maintain a centralized logging system, where log messages are forwarded to a server over the network. To avoid message loss when the server is not available, it is advisable to configure an action queue for the forwarding action. This way, messages that failed to be sent are stored locally until the server is reachable again. Note that such queues are not configurable for connections using the UD P protocol. To establish a fully reliable connection, for example when your logging server is outside of your private network, consider using the RELP protocol described in Section 20.5.4, “ Using RELP” . Pro ced u re 20.1. Fo rward in g T o a Sin g le Server Suppose the task is to forward log messages from the system to a server with host name example.com, and to configure an action queue to buffer the messages in case of a server outage. To do so, perform the following steps: 1. Create a working directory to store the queue files. For example: ~]# mkd i r /rsysl o g /wo rk/ 2. Use the following configuration in /etc/rsysl o g . co nf or create a file with the following content in the /etc/rsysl o g . d / directory: 388 Chapt er 2 0 . Viewing and Managing Log Files $WorkDirectory /rsyslog/work $ActionQueueType LinkedList $ActionQueueFileName example_fwd $ActionResumeRetryCount -1 $ActionQueueSaveOnShutdown on *.* @ @ example.com:18 Where: the /rsysl o g /wo rk/ directory created in the previous step is marked as a working directory, $Acti o nQ ueueT ype enables a LinkedList in-memory queue, $Acti o nFi l eName defines a disk storage, in this case the backup files are created in the /rsysl o g /wo rk/ directory with the example_fwd prefix, the $Acti o nR esumeR etryC o unt -1 setting prevents rsyslog form dropping messages when retrying to connect if server is not responding, enabled $Acti o nQ ueueSaveO nShutd o wn saves in-memory data if rsyslog shuts down, the last line forwards all received messages to the logging server, port specification is optional. With the above configuration, rsyslog keeps messages in memory if the remote server is not reachable. A file on disk is created only if rsyslog runs out of the configured memory queue space or needs to shut down, which benefits the system performance. Pro ced u re 20.2. Fo rward in g T o Mu lt ip le Servers The process of forwarding log messages to multiple servers is similar to the previous procedure: 1. Create a working directory for rsyslog to store the queue files. For example: ~]# mkd i r /rsysl o g /wo rk/ 2. Each destination server requires a separate forwarding rule, action queue specification, and backup file on disk. For example, use the following configuration in /etc/rsysl o g . co nf or create a file with the following content in the /etc/rsysl o g . d / directory: $WorkDirectory /rsyslog/work $ActionQueueType LinkedList $ActionQueueFileName example_fwd1 $ActionResumeRetryCount -1 $ActionQueueSaveOnShutdown on *.* @ @ example1.com $ActionQueueType LinkedList $ActionQueueFileName example_fwd2 $ActionResumeRetryCount -1 $ActionQueueSaveOnShutdown on *.* @ @ example2.com 389 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 20.3.2. Managing Queues All types of queues can be further configured to match your requirements. You can use several directives to modify both action queues and the main message queue. Currently, there are more than 20 queue parameters available, see Section 20.11, “ Online D ocumentation” . Some of these settings are used commonly, others, such as worker thread management, provide closer control over the queue behavior and are reserved for advanced users. With advanced settings, you can optimize rsyslo g 's performance, schedule queuing, or modify the behavior of queue on system shutdown. Lim it ing Que ue Size You can limit the number of messages that queue can contain with the following setting: $objectQueueHighWatermark number Replace object with Mai nMsg or with Acti o n to use this option to the main message queue or for an action queue respectively. Replace number with a number of enqueued messages. You can set the queue size only as the number of messages, not as their actual memory size. The default queue size is 10,000 messages for the main message queue and ruleset queues, and 1000 for action queues. D isk assisted queues are unlimited by default and can not be restricted with this directive, but you can reserve them physical disk space in bytes with the following settings: $objectQueueMaxDiscSpace number Replace object with Mai nMsg or with Acti o n. When the size limit specified by number is hit, messages are discarded until sufficient amount of space is freed by dequeued messages. Discarding Me ssage s When a queue reaches a certain number of messages, you can discard less important messages in order to save space in the queue for entries of higher priority. The threshold that launches the discarding process can be set with the so-called discard mark: $objectQueueDiscardMark number Replace object with Mai nMsg or with Acti o n to use this option to the main message queue or for an action queue respectively. Here, number stands for a number of messages that have to be in the queue to start the discarding process. To define which messages to discard, use: $objectQueueDiscardSeverity priority Replace priority with one of the following keywords (or with a number): d ebug (7), i nfo (6), no ti ce (5), warni ng (4), err (3), cri t (2), al ert (1), and emerg (0). With this setting, both newly incoming and already queued messages with lower than defined priority are erased from the queue immediately after the discard mark is reached. Using T im e fram e s You can configure rsyslo g to process queues during a specific time period. With this option you can, for example, transfer some processing into off-peak hours. To define a time frame, use the following syntax: 390 Chapt er 2 0 . Viewing and Managing Log Files $objectQueueDequeueTimeBegin hour $objectQueueDequeueTimeEnd hour With hour you can specify hours that bound your time frame. Use the 24-hour format without minutes. Co nfiguring Wo rke r T hre ads A worker thread performs a specified action on the enqueued message. For example, in the main message queue, a worker task is to apply filter logic to each incoming message and enqueue them to the relevant action queues. When a message arrives, a worker thread is started automatically. When the number of messages reaches a certain number, another worker thread is turned on. To specify this number, use: $objectQueueWorkerThreadMinimumMessages number Replace number with a number of messages that will trigger a supplemental worker thread. For example, with number set to 100, a new worker thread is started when more than 100 messages arrive. When more than 200 messages arrive, the third worker thread starts and so on. However, too many working threads running in parallel becomes ineffective, so you can limit the maximum number of them by using: $objectQueueWorkerThreads number where number stands for a maximum number of working threads that can run in parallel. For the main message queue, the default limit is 1 thread. Once a working thread has been started, it keeps running until an inactivity timeout appears. To set the length of timeout, type: $objectQueueWorkerTimeoutThreadShutdown time Replace time with the duration set in milliseconds. Without this setting, a zero timeout is applied and a worker thread is terminated immediately when it runs out of messages. If you specify time as -1, no thread will be closed. Bat ch De que uing To increase performance, you can configure rsyslo g to dequeue multiple messages at once. To set the upper limit for such dequeueing, use: $objectQueueDequeueBatchSize number Replace number with the maximum number of messages that can be dequeued at once. Note that a higher setting combined with a higher number of permitted working threads results in greater memory consumption. T e rm inat ing Que ue s When terminating a queue that still contains messages, you can try to minimize the data loss by specifying a time interval for worker threads to finish the queue processing: $objectQueueTimeoutShutdown time 391 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Specify time in milliseconds. If after that period there are still some enqueued messages, workers finish the current data element and then terminate. Unprocessed messages are therefore lost. Another time interval can be set for workers to finish the final element: $objectQueueTimeoutActionCompletion time In case this timeout expires, any remaining workers are shut down. To save data at shutdown, use: $objectQueueTimeoutSaveOnShutdown time If set, all queue elements are saved to disk before rsyslo g terminates. 20.4 . Configuring rsyslog on a Logging Server The rsysl o g service provides facilities both for running a logging server and for configuring individual systems to send their log files to the logging server. See Example 20.12, “ Reliable Forwarding of Log Messages to a Server” for information on client rsyslog configuration. The rsysl o g service must be installed on the system that you intend to use as a logging server and all systems that will be configured to send logs to it. Rsyslog is installed by default in Red Hat Enterprise Linux 7. If required, to ensure that it is, enter the following command as ro o t: ~]# yum i nstal l rsysl o g The steps in this procedure must be followed on the system that you intend to use as your logging server. All steps in this procedure must be made as the ro o t user: 1. Configure the firewall to allow rsysl o g T C P traffic. a. The default port for rsysl o g T C P traffic is 514 . To allow T C P traffic on this port, enter a command as follows: ~]# fi rewal l -cmd --zo ne= zone --ad d -po rt= 514 /tcp success Where zone is the zone of the interface to use. 2. Open the /etc/rsysl o g . co nf file in a text editor and proceed as follows: a. Add these lines below the modules section but above the P ro vi d es UD P sysl o g recepti o n section: # Define templates before the rules that use them ### Per-Host Templates for Remote Systems ### $template TmplAuth, "/var/log/remote/auth/%HOSTNAME%/%PROGRAMNAME:::secpathreplace%.log" $template TmplMsg, "/var/log/remote/msg/%HOSTNAME%/%PROGRAMNAME:::secpathreplace%.log" b. Replace the default P ro vi d es T C P sysl o g recepti o n section with the following: 392 Chapt er 2 0 . Viewing and Managing Log Files # Provides TCP syslog reception $ModLoad imtcp # Adding this ruleset to process remote messages $RuleSet remote1 authpriv.* ?TmplAuth *.info;mail.none;authpriv.none;cron.none ?TmplMsg $RuleSet RSYSLOG_DefaultRuleset #End the rule set by switching back to the default rule set $InputTCPServerBindRuleset remote1 #Define a new input and bind it to the "remote1" rule set $InputTCPServerRun 514 Save the changes to the /etc/rsysl o g . co nf file. 3. The rsysl o g service must be running on both the logging server and the systems attempting to log to it. a. Use the systemctl command to start the rsysl o g service. ~]# systemctl start rsysl o g b. To ensure the rsysl o g service starts automatically in future, enter the following command as root: ~]# systemctl enabl e rsysl o g Your log server is now configured to receive and store log files from the other systems in your environment. 20.5. Using Rsyslog Modules D ue to its modular design, rsyslo g offers a variety of modules which provide additional functionality. Note that modules can be written by third parties. Most modules provide additional inputs (see Input Modules below) or outputs (see Output Modules below). Other modules provide special functionality specific to each module. The modules may provide additional configuration directives that become available after a module is loaded. To load a module, use the following syntax: $ModLoad MODULE where $Mo d Lo ad is the global directive that loads the specified module and MODULE represents your desired module. For example, if you want to load the Text File Input Module (i mfi l e) that enables rsyslo g to convert any standard text files into syslog messages, specify the following line in the /etc/rsysl o g . co nf configuration file: $ModLoad imfile rsyslo g offers a number of modules which are split into the following main categories: Input Modules — Input modules gather messages from various sources. The name of an input module always starts with the i m prefix, such as i mfi l e and i mjo urnal . Output Modules — Output modules provide a facility to issue message to various targets such as sending across a network, storing in a database, or encrypting. The name of an output module always starts with the o m prefix, such as o msnmp, o mrel p, etc. 393 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Parser Modules — These modules are useful in creating custom parsing rules or to parse malformed messages. With moderate knowledge of the C programming language, you can create your own message parser. The name of a parser module always starts with the pm prefix, such as pmrfc54 24 , pmrfc316 4 , and so on. Message Modification Modules — Message modification modules change content of syslog messages. Names of these modules start with the mm prefix. Message Modification Modules such as mmano n, mmno rmal i ze, or mmjso nparse are used for anonymization or normalization of messages. String Generator Modules — String generator modules generate strings based on the message content and strongly cooperate with the template feature provided by rsyslo g . For more information on templates, see Section 20.2.3, “ Templates” . The name of a string generator module always starts with the sm prefix, such as smfi l e or smtrad fi l e. Library Modules — Library modules provide functionality for other loadable modules. These modules are loaded automatically by rsyslo g when needed and cannot be configured by the user. A comprehensive list of all available modules and their detailed description can be found at http://www.rsyslog.com/doc/rsyslog_conf_modules.html. Warning Note that when rsyslo g loads any modules, it provides them with access to some of its functions and data. This poses a possible security threat. To minimize security risks, use trustworthy modules only. 20.5.1. Import ing T ext Files The Text File Input Module, abbreviated as i mfi l e, enables rsyslo g to convert any text file into a stream of syslog messages. You can use i mfi l e to import log messages from applications that create their own text file logs. To load i mfi l e, add the following into etc/rsysl o g . co nf: $ModLoad imfile $InputFilePollInterval int It is sufficient to load i mfi l e once, even when importing multiple files. The $InputFilePollInterval global directive specifies how often rsyslo g checks for changes in connected text files. The default interval is 10 seconds, to change it, replace int with a time interval specified in seconds. To identify the text files to import, use the following syntax in /etc/rsysl o g . co nf: # File 1 $InputFileName path_to_file $InputFileTag tag: $InputFileStateFile state_file_name $InputFileSeverity severity $InputFileFacility facility $InputRunFileMonitor # File 2 $InputFileName path_to_file2 ... 394 Chapt er 2 0 . Viewing and Managing Log Files Four settings are required to specify an input text file: replace path_to_file with a path to the text file. replace tag: with a tag name for this message. replace state_file_name with a unique name for the state file. State files, which are stored in the rsyslog working directory, keep cursors for the monitored files, marking what partition has already been processed. If you delete them, whole files will be read in again. Make sure that you specify a name that does not already exist. add the $InputRunFileMonitor directive that enables the file monitoring. Without this setting, the text file will be ignored. Apart from the required directives, there are several other settings that can be applied on the text input. Set the severity of imported messages by replacing severity with an appropriate keyword. Replace facility with a keyword to define the subsystem that produced the message. The keywords for severity and facility are the same as those used in facility/priority-based filters, see Section 20.2.1, “ Filters” . Examp le 20.13. Imp o rt in g T ext Files The Apache HTTP server creates log files in text format. To apply the processing capabilities of rsyslo g to apache error messages, first use the i mfi l e module to import the messages. Add the following into /etc/rsysl o g . co nf: $ModLoad imfile $InputFileName /var/log/httpd/error_log $InputFileTag apache-error: $InputFileStateFile state-apache-error $InputRunFileMonitor 20.5.2. Export ing Messages t o a Dat abase Processing of log data can be faster and more convenient when performed in a database rather than with text files. Based on the type of D BMS used, choose from various output modules such as o mmysq l , o mpg sq l , o mo racl e, or o mmo ng o d b. As an alternative, use the generic o ml i bd bi output module that relies on the l i bd bi library. The o ml i bd bi module supports database systems Firebird/Interbase, MS SQL, Sybase, SQLite, Ingres, Oracle, mSQL, MySQL, and PostgreSQL. Examp le 20.14 . Exp o rt in g R syslo g Messag es t o a D at ab ase To store the rsyslog messages in a MySQL database, add the following into /etc/rsysl o g . co nf: $ModLoad ommysql $ActionOmmysqlServerPort 1234 *.* :ommysql:database-server,database-name,database-userid,databasepassword 395 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide First, the output module is loaded, then the communication port is specified. Additional information, such as name of the server and the database, and authentication data, is specified on the last line of the above example. 20.5.3. Enabling Encrypt ed T ransport Confidentiality and integrity in network transmissions can be provided by either the TLS or GSSAPI encryption protocol. Transport Layer Security (TLS) is a cryptographic protocol designed to provide communication security over the network. When using TLS, rsyslog messages are encrypted before sending, and mutual authentication exists between the sender and receiver. Generic Security Service API (GSSAPI) is an application programming interface for programs to access security services. To use it in connection with rsyslo g you must have a functioning K erb ero s environment. 20.5.4 . Using RELP Reliable Event Logging Protocol (RELP) is a networking protocol for data logging in computer networks. It is designed to provide reliable delivery of event messages, which makes it useful in environments where message loss is not acceptable. 20.6. Int eract ion of Rsyslog and Journal As mentioned above, R syslo g and Jo u rn al, the two logging applications present on your system, have several distinctive features that make them suitable for specific use cases. In many situations it is useful to combine their capabilities, for example to create structured messages and store them in a file database (see Section 20.7, “ Structured Logging with Rsyslog” ). A communication interface needed for this cooperation is provided by input and output modules on the side of R syslo g and by the Jo u rn al's communication socket. By default, rsysl o g d uses the i mjo urnal module as a default input mode for journal files. With this module, you import not only the messages but also the structured data provided by jo urnal d . Also, older data can be imported from jo urnal d (unless forbidden with the $Imjo urnal Ig no reP revi o usMessag es directive). See Section 20.7.1, “ Importing D ata from Journal” for basic configuration of i mjo urnal . As an alternative, configure rsysl o g d to read from the socket provided by jo urnal as an output for syslog-based applications. The path to the socket is /run/systemd /jo urnal /sysl o g . Use this option when you want to maintain plain rsyslog messages. Compared to i mjo urnal the socket input currently offers more features, such as ruleset binding or filtering. To import Jo u rn al data trough the socket, use the following configuration in /etc/rsysl o g . co nf: $ModLoad imuxsock $OmitLocalLogging off The above syntax loads the i muxso ck module and turns off the $O mi tLo cal Lo g g i ng directive, which enables the import trough the system socket. The path to this socket is specified separately in /etc/rsysl o g . d /l i sten. co nf as follows: $SystemLogSocketName /run/systemd/journal/syslog You can also output messages from R syslo g to Jo u rn al with the o mjo urnal module. Configure 396 Chapt er 2 0 . Viewing and Managing Log Files the output in /etc/rsysl o g . co nf as follows: $ModLoad omjournal *.* :omjournal: For instance, the following configuration forwards all received messages on tcp port 10514 to the Journal: $ModLoad imtcp $ModLoad omjournal $RuleSet remote *.* :omjournal: $InputTCPServerBindRuleset remote $InputTCPServerRun 10514 20.7. St ruct ured Logging wit h Rsyslog On systems that produce large amounts of log data, it can be convenient to maintain log messages in a structured format. With structured messages, it is easier to search for particular information, to produce statistics and to cope with changes and inconsistencies in message structure. R syslo g uses the JSON (JavaScript Object Notation) format to provide structure for log messages. Compare the following unstructured log message: Oct 25 10:20:37 localhost anacron[1395]: Jobs will be executed sequentially with a structured one: {"timestamp":"2013-10-25T10:20:37", "host":"localhost", "program":"anacron", "pid":"1395", "msg":"Jobs will be executed sequentially"} Searching structured data with use of key-value pairs is faster and more precise than searching text files with regular expressions. The structure also lets you to search for the same entry in messages produced by various applications. Also, JSON files can be stored in a document database such as MongoD B, which provides additional performance and analysis capabilities. On the other hand, a structured message requires more disk space than the unstructured one. In rsyslo g , log messages with meta data are pulled from Jo u rn al with use of the i mjo urnal module. With the mmjso nparse module, you can parse data imported from Jo u rn al and from other sources and process them further, for example as a database output. For parsing to be successful, mmjso nparse requires input messages to be structured in a way that is defined by the Lu mb erjack project. The Lu mb erjack project aims to add structured logging to rsyslo g in a backward-compatible way. To identify a structured message, Lu mb erjack specifies the @ cee: string that prepends the actual JSON structure. Also, Lu mb erjack defines the list of standard field names that should be used for entities in the JSON string. For more information on Lu mb erjack, see Section 20.11, “ Online D ocumentation” . 397 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The following is an example of a lumberjack-formatted message: @ cee: {"pid":17055, "uid":1000, "gid":1000, "appname":"logger", "msg":"Message text."} To build this structure inside R syslo g , a template is used, see Section 20.7.2, “ Filtering Structured Messages” . Applications and servers can employ the l i bumberl o g library to generate messages in the lumberjack-compliant form. For more information on l i bumberl o g , see Section 20.11, “ Online D ocumentation” . 20.7.1. Import ing Dat a from Journal The i mjo urnal module is R syslo g 's input module to natively read the journal files (see Section 20.6, “ Interaction of Rsyslog and Journal” ). Journal messages are then logged in text format as other rsyslog messages. However, with further processing, it is possible to translate meta data provided by Jo u rn al into a structured message. To import data from Jo u rn al to R syslo g , use the following configuration in /etc/rsysl o g . co nf: $ModLoad imjournal $imjournalPersistStateInterval number_of_messages $imjournalStateFile path $imjournalRatelimitInterval seconds $imjournalRatelimitBurst burst_number $ImjournalIgnorePreviousMessages off/on With number_of_messages, you can specify how often the journal data must be saved. This will happen each time the specified number of messages is reached. Replace path with a path to the state file. This file tracks the journal entry that was the last one processed. With seconds, you set the length of the rate limit interval. The number of messages processed during this interval can not exceed the value specified in burst_number. The default setting is 20,000 messages per 600 seconds. Rsyslog discards messages that come after the maximum burst within the time frame specified. With $Imjo urnal Ig no reP revi o usMessag es you can ignore messages that are currently in Journal and import only new messages, which is used when there is no state file specified. The default setting is o ff. Please note that if this setting is off and there is no state file, all messages in the Journal are processed, even if they were already processed in a previous rsyslog session. 398 Chapt er 2 0 . Viewing and Managing Log Files Note You can use i mjo urnal simultaneously with i muxso ck module that is the traditional system log input. However, to avoid message duplication, you must prevent i muxso ck from reading the Journal's system socket. To do so, use the $O mi tLo cal Lo g g i ng directive: $ModLoad imuxsock $ModLoad imjournal $OmitLocalLogging on $AddUnixListenSocket /run/systemd/journal/syslog You can translate all data and meta data stored by Jo u rn al into structured messages. Some of these meta data entries are listed in Example 20.16, “ Verbose journalctl Output” , for a complete list of journal fields see the systemd . jo urnal -fi el d s(7) manual page. For example, it is possible to focus on kernel journal fields, that are used by messages originating in the kernel. 20.7.2. Filt ering St ruct ured Messages To create a lumberjack-formatted message that is required by rsyslo g 's parsing module, use the following template: template(name="CEETemplate" type="string" string="%TIMESTAMP% %HOSTNAME% %syslogtag% @ cee: %$!all-json%\n") This template prepends the @ cee: string to the JSON string and can be applied, for example, when creating an output file with o mfi l e module. To access JSON field names, use the $! prefix. For example, the following filter condition searches for messages with specific hostname and UID: ($!hostname == "hostname" & & $!UID== "UID") 20.7.3. Parsing JSON The mmjso nparse module is used for parsing structured messages. These messages can come from Jo u rn al or from other input sources, and must be formatted in a way defined by the Lu mb erjack project. These messages are identified by the presence of the @ cee: string. Then, mmjso nparse checks if the JSON structure is valid and then the message is parsed. To parse lumberjack-formatted JSON messages with mmjso nparse, use the following configuration in the /etc/rsysl o g . co nf: $ModLoad mmjsonparse *.* :mmjsonparse: In this example, the mmjso nparse module is loaded on the first line, then all messages are forwarded to it. Currently, there are no configuration parameters available for mmjso nparse. 20.7.4 . St oring Messages in t he MongoDB 399 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide R syslo g supports storing JSON logs in the MongoD B document database through the ommongodb output module. To forward log messages into MongoD B, use the following syntax in the /etc/rsysl o g . co nf (configuration parameters for ommongodb are available only in the new configuration format; see Section 20.2.6, “ Using the New Configuration Format” ): $ModLoad ommongodb *.* action(type="ommongodb" server="DB_server" serverport="port" db="DB_name" collection="collection_name" uid="UID" pwd="password") Replace DB_server with the name or address of the MongoD B server. Specify port to select a nonstandard port from the MongoD B server. The default port value is 0 and usually there is no need to change this parameter. With DB_name, you identify to which database on the MongoD B server you want to direct the output. Replace collection_name with the name of a collection in this database. In MongoD B, collection is a group of documents, the equivalent of an RD BMS table. You can set your login details by replacing UID and password. You can shape the form of the final database output with use of templates. By default, ryslo g uses a template based on standard lu mb erjack field names. 20.8. Debugging Rsyslog To run rsysl o g d in debugging mode, use the following command: rsysl o g d -d n With this command, rsysl o g d produces debugging information and prints it to the standard output. The -n stands for " no fork" . You can modify debugging with environmental variables, for example, you can store the debug output in a log file. Before starting rsysl o g d , type the following on the command line: export RSYSLOG_DEBUGLOG="path" export RSYSLOG_DEBUG="Debug" Replace path with a desired location for the file where the debugging information will be logged. For a complete list of options available for the RSYSLOG_D EBUG variable, see the related section in the rsysl o g d (8) manual page. To check if syntax used in the etc/rsysl o g . co nf file is valid use: rsysl o g d -N 1 Where 1 represents level of verbosity of the output message. This is a forward compatibility option because currently, only one level is provided. However, you must add this argument to run the validation. 20.9. Using t he Journal The Journal is a component of syst emd that is responsible for viewing and management of log files. 4 00 Chapt er 2 0 . Viewing and Managing Log Files It can be used in parallel, or in place of a traditional syslog daemon, such as rsysl o g d . The Journal was developed to address problems connected with traditional logging. It is closely integrated with the rest of the system, supports various logging technologies and access management for the log files. Logging data is collected, stored, and processed by the Journal's jo urnal d service. It creates and maintains binary files called journals based on logging information that is received from the kernel, from user processes, from standard output, and standard error output of system services or via its native API. These journals are structured and indexed, which provides relatively fast seek times. Journal entries can carry a unique identifier. The jo urnal d service collects numerous meta data fields for each log message. The actual journal files are secured, and therefore cannot be manually edited. 20.9.1. Viewing Log Files To access the journal logs, use the jo u rn alct l tool. For a basic view of the logs type as ro o t: jo urnal ctl An output of this command is a list of all log files generated on the system including messages generated by system components and by users. The structure of this output is similar to one used in /var/l o g /messag es/ but with certain improvements: the priority of entries is marked visually. Lines of error priority and higher are highlighted with red color and a bold font is used for lines with notice and warning priority the time stamps are converted for the local time zone of your system all logged data is shown, including rotated logs the beginning of a boot is tagged with a special line Examp le 20.15. Examp le O u t p u t o f jo u rn alct l The following is an example output provided by the jo u rn alct l tool. When called without parameters, the listed entries begin with a time stamp, then the host name and application that performed the operation is mentioned followed by the actual message. This example shows the first three entries in the journal log: # jo urnal ctl -- Logs begin at Thu 2013-08-01 15:42:12 CEST, 15:48:48 CEST. -Aug 01 15:42:12 localhost systemd-journal[54]: files to grow to 49.7M. Aug 01 15:42:12 localhost kernel: Initializing Aug 01 15:42:12 localhost kernel: Initializing end at Thu 2013-08-01 Allowing runtime journal cgroup subsys cpuset cgroup subsys cpu [...] In many cases, only the latest entries in the journal log are relevant. The simplest way to reduce jo urnal ctl output is to use the -n option that lists only the specified number of most recent log entries: jo urnal ctl -n Number 4 01 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Replace Number with the number of lines to be shown. When no number is specified, jo urnal ctl displays the ten most recent entries. The jo urnal ctl command allows controlling the form of the output with the following syntax: jo urnal ctl -o form Replace form with a keyword specifying a desired form of output. There are several options, such as verbo se, which returns full-structured entry items with all fields, expo rt, which creates a binary stream suitable for backups and network transfer, and jso n, which formats entries as JSON data structures. For the full list of keywords, see the jo urnal ctl (1) manual page. Examp le 20.16 . Verb o se jo u rn alct l O u t p u t To view full meta data about all entries, type: # jo urnal ctl -o verbo se [...] Fri 2013-08-02 14:41:22 CEST [s=e1021ca1b81e4fc688fad6a3ea21d35b;i=55c;b=78c81449c920439da57da7bd5c56 a770;m=27cc _BOOT_ID=78c81449c920439da57da7bd5c56a770 PRIORITY=5 SYSLOG_FACILITY=3 _TRANSPORT=syslog _MACHINE_ID=69d27b356a94476da859461d3a3bc6fd _HOSTNAME=localhost.localdomain _PID=562 _COMM=dbus-daemon _EXE=/usr/bin/dbus-daemon _CMDLINE=/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation _SYSTEMD_CGROUP=/system/dbus.service _SYSTEMD_UNIT=dbus.service SYSLOG_IDENTIFIER=dbus SYSLOG_PID=562 _UID=81 _GID=81 _SELINUX_CONTEXT=system_u:system_r:system_dbusd_t:s0-s0:c0.c1023 MESSAGE=[system] Successfully activated service 'net.reactivated.Fprint' _SOURCE_REALTIME_TIMESTAMP=1375447282839181 [...] This example lists fields that identify a single log entry. These meta data can be used for message filtering as shown in Section 20.9.4, “ Advanced Filtering” . For a complete description of all possible fields see the systemd . jo urnal -fi el d s(7) manual page. 20.9.2. Access Cont rol By default, Jo u rn al users without ro o t privileges can only see log files generated by them. The system administrator can add selected users to the adm group, which grants them access to complete 4 02 Chapt er 2 0 . Viewing and Managing Log Files log files. To do so, type as ro o t: usermo d -a -G adm username Here, replace username with a name of the user to be added to the adm group. This user then receives the same output of the jo urnal ctl command as the root user. Note that access control only works when persistent storage is enabled for Jo u rn al. 20.9.3. Using T he Live View When called without parameters, jo urnal ctl shows the full list of entries, starting with the oldest entry collected. With the live view, you can supervise the log messages in real time as new entries are continuously printed as they appear. To start jo u rn alct l in live view mode, type: jo urnal ctl -f This command returns a list of the ten most current log lines. The jo u rn alct l utility then stays running and waits for new changes to show them immediately. 20.9.4 . Filt ering Messages The output of the jo urnal ctl command executed without parameters is often extensive, therefore you can use various filtering methods to extract information to meet your needs. Filt e ring by Prio rit y Log messages are often used to track erroneous behavior on the system. To view only entries with a selected or higher priority, use the following syntax: jo urnal ctl -p priority Here, replace priority with one of the following keywords (or with a number): d ebug (7), i nfo (6), no ti ce (5), warni ng (4), err (3), cri t (2), al ert (1), and emerg (0). Examp le 20.17. Filt erin g b y Prio rit y To view only entries with error or higher priority, use: jo urnal ctl -p err Filt e ring by T im e To view log entries only from the current boot, type: jo urnal ctl -b If you reboot your system just occasionally, the -b will not significantly reduce the output of jo urnal ctl . In such cases, time-based filtering is more helpful: jo urnal ctl --si nce=value --unti l =value 4 03 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide With --si nce and --unti l , you can view only log messages created within a specified time range. You can pass values to these options in form of date or time or both as shown in the following example. Examp le 20.18. Filt erin g b y T ime an d Prio rit y Filtering options can be combined to reduce the set of results according to specific requests. For example, to view the warning or higher priority messages from a certain point in time, type: jo urnal ctl -p warni ng --si nce= "20 13-3-16 23: 59 : 59 " Advance d Filt e ring Example 20.16, “ Verbose journalctl Output” lists a set of fields that specify a log entry and can all be used for filtering. For a complete description of meta data that systemd can store, see the systemd . jo urnal -fi el d s(7) manual page. This meta data is collected for each log message, without user intervention. Values are usually text-based, but can take binary and large values; fields can have multiple values assigned though it is not very common. To view a list of unique values that occur in a specified field, use the following syntax: jo urnal ctl -F fieldname Replace fieldname with a name of a field you are interested in. To show only log entries that fit a specific condition, use the following syntax: jo urnal ctl fieldname=value Replace fieldname with a name of a field and value with a specific value contained in that field. As a result, only lines that match this condition are returned. Note As the number of meta data fields stored by systemd is quite large, it is easy to forget the exact name of the field of interest. When unsure, type: jo urnal ctl and press the T ab key two times. This shows a list of available field names. T ab completion based on context works on field names, so you can type a distinctive set of letters from a field name and then press T ab to complete the name automatically. Similarly, you can list unique values from a field. Type: jo urnal ctl fieldname= and press T ab two times. This serves as an alternative to jo urnal ctl -F fieldname. You can specify multiple values for one field: 4 04 Chapt er 2 0 . Viewing and Managing Log Files jo urnal ctl fieldname=value1 fieldname=value2 ... Specifying two matches for the same field results in a logical O R combination of the matches. Entries matching value1 or value2 are displayed. Also, you can specify multiple field-value pairs to further reduce the output set: jo urnal ctl fieldname1=value fieldname2=value ... If two matches for different field names are specified, they will be combined with a logical AND . Entries have to match both conditions to be shown. With use of the + symbol, you can set a logical O R combination of matches for multiple fields: jo urnal ctl fieldname1=value + fieldname2=value ... This command returns entries that match at least one of the conditions, not only those that match both of them. Examp le 20.19 . Ad van ced f ilt erin g To display entries created by avahi -d aemo n. servi ce or cro nd . servi ce under user with UID 70, use the following command: jo urnal ctl _UID = 70 _SY ST EMD _UNIT = avahi -d aemo n. servi ce _SY ST EMD _UNIT = cro nd . servi ce Since there are two values set for the _SY ST EMD _UNIT field, both results will be displayed, but only when matching the _UID = 70 condition. This can be expressed simply as: (UID =70 and (avahi or cron)). You can apply the aforementioned filtering also in the live-view mode to keep track of the latest changes in the selected group of log entries: jo urnal ctl -f fieldname=value ... 20.9.5. Enabling Persist ent St orage By default, Jo u rn al stores log files only in memory or a small ring-buffer in the /run/l o g /jo urnal / directory. This is sufficient to show recent log history with jo urnal ctl . This directory is volatile, log data is not saved permanently. With the default configuration, syslog reads the journal logs and stores them in the /var/l o g / directory. With persistent logging enabled, journal files are stored in /var/l o g /jo urnal which means they persist after reboot. Journal can then replace rsyslo g for some users (but see the chapter introduction). Enabled persistent storage has the following advantages Richer data is recorded for troubleshooting in a longer period of time For immediate troubleshooting, richer data is available after a reboot Server console currently reads data from journal, not log files Persistent storage has also certain disadvantages: 4 05 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Even with persistent storage the amount of data stored depends on free memory, there is no guarantee to cover a specific time span More disk space is needed for logs To enable persistent storage for Journal, create the journal directory manually as shown in the following example. As ro o t type: mkd i r -p /var/l o g /jo urnal Then, restart jo urnal d to apply the change: systemctl restart systemd -jo urnal d 20.10. Managing Log Files in a Graphical Environment As an alternative to the aforementioned command-line utilities, Red Hat Enterprise Linux 7 provides an accessible GUI for managing log messages. 20.10.1. Viewing Log Files Most log files are stored in plain text format. You can view them with any text editor such as Vi or Emacs. Some log files are readable by all users on the system; however, root privileges are required to read most log files. To view system log files in an interactive, real-time application, use the Syst em Lo g . Note In order to use the Syst em Lo g , first ensure the gnome-system-log package is installed on your system by running, as ro o t: ~]# yum i nstal l g no me-system-l o g For more information on installing packages with Yum, see Section 7.2.4, “ Installing Packages” . After you have installed the gnome-system-log package, open the Syst em Lo g by clicking Ap p licat io n s → Syst em T o o ls → Syst em Lo g , or type the following command at a shell prompt: ~]$ g no me-system-l o g The application only displays log files that exist; thus, the list might differ from the one shown in Figure 20.2, “ System Log” . 4 06 Chapt er 2 0 . Viewing and Managing Log Files Fig u re 20.2. Syst em Lo g The Syst em Lo g application lets you filter any existing log file. Click on the button marked with the gear symbol to view the menu, select Filt ers → Man ag e Filt ers to define or edit the desired filter. Fig u re 20.3. Syst em Lo g - Filt ers Adding or editing a filter lets you define its parameters as is shown in Figure 20.4, “ System Log defining a filter” . 4 07 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 20.4 . Syst em Lo g - d ef in in g a f ilt er When defining a filter, the following parameters can be edited: Name — Specifies the name of the filter. R eg ul ar Expressi o n — Specifies the regular expression that will be applied to the log file and will attempt to match any possible strings of text in it. Effect Hi g hl i g ht — If checked, the found results will be highlighted with the selected color. You may select whether to highlight the background or the foreground of the text. Hi d e — If checked, the found results will be hidden from the log file you are viewing. When you have at least one filter defined, it can be selected from the Fi l ters menu and it will automatically search for the strings you have defined in the filter and highlight or hide every successful match in the log file you are currently viewing. 4 08 Chapt er 2 0 . Viewing and Managing Log Files Fig u re 20.5. Syst em Lo g - en ab lin g a f ilt er When you select the Sho w matches o nl y option, only the matched strings will be shown in the log file you are currently viewing. 20.10.2. Adding a Log File To add a log file you want to view in the list, select File → O p en . This will display the O pen Lo g window where you can select the directory and file name of the log file you want to view. Figure 20.6, “ System Log - adding a log file” illustrates the O p en Lo g window. 4 09 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 20.6 . Syst em Lo g - ad d in g a lo g f ile Click on the O pen button to open the file. The file is immediately added to the viewing list where you can select it and view its contents. Note The Syst em Lo g also allows you to open log files zipped in the . g z format. 20.10.3. Monit oring Log Files Syst em Lo g monitors all opened logs by default. If a new line is added to a monitored log file, the log name appears in bold in the log list. If the log file is selected or displayed, the new lines appear in bold at the bottom of the log file. Figure 20.7, “ System Log - new log alert” illustrates a new alert in the cro n log file and in the messag es log file. Clicking on the messag es log file displays the logs in the file with the new lines in bold. 4 10 Chapt er 2 0 . Viewing and Managing Log Files Fig u re 20.7. Syst em Lo g - n ew lo g alert 20.11. Addit ional Resources For more information on how to configure the rsysl o g daemon and how to locate, view, and monitor log files, see the resources listed below. Inst alled Document at ion rsysl o g d (8) — The manual page for the rsysl o g d daemon documents its usage. rsysl o g . co nf(5) — The manual page named rsysl o g . co nf documents available configuration options. l o g ro tate(8) — The manual page for the lo g ro t at e utility explains in greater detail how to configure and use it. jo urnal ctl (1) — The manual page for the jo urnal ctl daemon documents its usage. jo urnal d . co nf(5) — This manual page documents available configuration options. systemd . jo urnal -fi el d s(7) — This manual page lists special Jo u rn al fields. Online Document at ion The rsyslo g home page offers additional documentation, configuration examples, and video tutorials. Make sure to consult the documents relevant to the version you are using: 4 11 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide RainerScript documentation on the rsyslog Home Page — Commented summary of data types, expressions, and functions available in RainerScript. rsyslog version 7 documentation on the rsyslog home page — Version 7 of rsyslo g is available for Red Hat Enterprise Linux 7 in the rsyslog7 package. D escription of queues on the rsyslog home Page — General information on various types of message queues and their usage. See Also Chapter 4, Gaining Privileges documents how to gain administrative privileges by using the su and sud o commands. Chapter 8, Managing Services with systemd provides more information on systemd and documents how to use the systemctl command to manage system services. 4 12 Chapt er 2 1 . Aut omat ing Syst em T asks Chapter 21. Automating System Tasks Tasks, also known as jobs, can be configured to run automatically within a specified period of time, on a specified date, or when the system load average decreases below 0.8. Red Hat Enterprise Linux is pre-configured to run important system tasks to keep the system updated. For example, the slocate database used by the l o cate command is updated daily. A system administrator can use automated tasks to perform periodic backups, monitor the system, run custom scripts, and so on. Red Hat Enterprise Linux comes with the following automated task utilities: cro n, anacro n, at, and batch. Every utility is intended for scheduling a different job type: while Cron and Anacron schedule recurring jobs, At and Batch schedule one-time jobs (refer to Section 21.1, “ Cron and Anacron” and Section 21.2, “ At and Batch” respectively). Red Hat Enterprise Linux 7 supports the use of systemd . ti mer for executing a job at a specific time. See man systemd . ti mer(5) for more information. 21.1. Cron and Anacron Both Cron and Anacron are daemons that can schedule execution of recurring tasks to a certain point in time defined by the exact time, day of the month, month, day of the week, and week. Cron jobs can run as often as every minute. However, the utility assumes that the system is running continuously and if the system is not on at the time when a job is scheduled, the job is not executed. On the other hand, Anacron remembers the scheduled jobs if the system is not running at the time when the job is scheduled. The job is then executed as soon as the system is up. However, Anacron can only run a job once a day. 21.1.1. Inst alling Cron and Anacron To install Cron and Anacron, you need to install the cronie package with Cron and the cronie-anacron package with Anacron (cronie-anacron is a sub-package of cronie). To determine if the packages are already installed on your system, issue the following command: rpm -q cro ni e cro ni e-anacro n The command returns full names of the cronie and cronie-anacron packages if already installed, or notifies you that the packages are not available. To install these packages, use the yum command in the following form as ro o t: yum i nstal l package For example, to install both Cron and Anacron, type the following at a shell prompt: ~]# yum i nstal l cro ni e cro ni e-anacro n For more information on how to install new packages in Red Hat Enterprise Linux, see Section 7.2.4, “ Installing Packages” . 4 13 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 21.1.2. Running t he Crond Service The cron and anacron jobs are both picked by the cro nd service. This section provides information on how to start, stop, and restart the cro nd service, and shows how to configure it to start automatically at boot time. For more information on how to manage system service in Red Hat Enterprise Linux 7 in general, see Chapter 8, Managing Services with systemd. 2 1 .1 .2 .1 . St art ing and St o pping t he Cro n Se rvice To determine if the service is running, use the following command: systemctl status cro nd . servi ce To run the cro nd service in the current session, type the following at a shell prompt as ro o t: systemctl start cro nd . servi ce To configure the service to start automatically at boot time, use the following command as ro o t: systemctl enabl e cro nd . servi ce 2 1 .1 .2 .2 . St o pping t he Cro n Se rvice To stop the cro nd service in the current session, type the following at a shell prompt as ro o t: systemctl sto p cro nd . servi ce To prevent the service from starting automatically at boot time, use the following command as ro o t: systemctl d i sabl e cro nd . servi ce 2 1 .1 .2 .3. Re st art ing t he Cro n Se rvice To restart the cro nd service, type the following at a shell prompt as ro o t: systemctl restart cro nd . servi ce This command stops the service and starts it again in quick succession. 21.1.3. Configuring Anacron Jobs The main configuration file to schedule jobs is the /etc/anacro ntab file, which can be only accessed by the ro o t user. The file contains the following: SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # the maximal random delay added to the base delay of the jobs RANDOM_DELAY=45 # the jobs will be started during the following hours only START_HOURS_RANGE=3-22 4 14 Chapt er 2 1 . Aut omat ing Syst em T asks #period in days delay in minutes job-identifier command 1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @ monthly 45 cron.monthly nice run-parts /etc/cron.monthly The first three lines define the variables that configure the environment in which the anacron tasks run: SHELL — shell environment used for running jobs (in the example, the Bash shell) P AT H — paths to executable programs MAILT O — username of the user who receives the output of the anacron jobs by email If the MAILT O variable is not defined (MAILT O = ), the email is not sent. The next two variables modify the scheduled time for the defined jobs: R AND O M_D ELAY — maximum number of minutes that will be added to the d el ay i n mi nutes variable which is specified for each job The minimum delay value is set, by default, to 6 minutes. If R AND O M_D ELAY is, for example, set to 12, then between 6 and 12 minutes are added to the d el ay i n mi nutes for each job in that particular anacrontab. R AND O M_D ELAY can also be set to a value below 6 , including 0 . When set to 0 , no random delay is added. This proves to be useful when, for example, more computers that share one network connection need to download the same data every day. ST AR T _HO UR S_R ANG E — interval, when scheduled jobs can be run, in hours In case the time interval is missed, for example due to a power failure, the scheduled jobs are not executed that day. The remaining lines in the /etc/anacro ntab file represent scheduled jobs and follow this format: period in days delay in minutes job-identifier command peri o d i n d ays — frequency of job execution in days The property value can be defined as an integer or a macro (@ d ai l y, @ weekl y, @ mo nthl y), where @ d ai l y denotes the same value as integer 1, @ weekl y the same as 7, and @ mo nthl y specifies that the job is run once a month regardless of the length of the month. d el ay i n mi nutes — number of minutes anacron waits before executing the job The property value is defined as an integer. If the value is set to 0 , no delay applies. jo b-i d enti fi er — unique name referring to a particular job used in the log files co mmand — command to be executed The command can be either a command such as l s /pro c >> /tmp/pro c or a command which executes a custom script. Any lines that begin with a hash sign (#) are comments and are not processed. 2 1 .1 .3.1 . Exam ple s o f Anacro n Jo bs 4 15 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The following example shows a simple /etc/anacro ntab file: SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # the maximal random delay added to the base delay of the jobs RANDOM_DELAY=30 # the jobs will be started during the following hours only START_HOURS_RANGE=16-20 #period in days delay in minutes job-identifier command 1 20 dailyjob nice run-parts /etc/cron.daily 7 25 weeklyjob /etc/weeklyjob.bash @ monthly 45 monthlyjob ls /proc >> /tmp/proc All jobs defined in this anacro ntab file are randomly delayed by 6-30 minutes and can be executed between 16:00 and 20:00. The first defined job is triggered daily between 16:26 and 16:50 (RAND OM_D ELAY is between 6 and 30 minutes; the delay in minutes property adds 20 minutes). The command specified for this job executes all present programs in the /etc/cro n. d ai l y/ directory using the run-parts script (the run-parts scripts accepts a directory as a command-line argument and sequentially executes every program in the directory). See the run-parts man page for more information on the run-parts script. The second job executes the weekl yjo b. bash script in the /etc/ directory once a week. The third job runs a command, which writes the contents of /pro c to the /tmp/pro c file (l s /pro c >> /tmp/pro c) once a month. 21.1.4 . Configuring Cron Jobs The configuration file for cron jobs is /etc/cro ntab, which can be only modified by the ro o t user. The file contains the following: SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # For details see man 4 crontabs # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed The first three lines contain the same variable definitions as an anacro ntab file: SHELL, P AT H, and MAILT O . For more information about these variables, see Section 21.1.3, “ Configuring Anacron Jobs” . 4 16 Chapt er 2 1 . Aut omat ing Syst em T asks In addition, the file can define the HO ME variable. The HO ME variable defines the directory, which will be used as the home directory when executing commands or scripts run by the job. The remaining lines in the /etc/cro ntab file represent scheduled jobs and have the following format: minute hour day month day of week username command The following define the time when the job is to be run: mi nute — any integer from 0 to 59 ho ur — any integer from 0 to 23 d ay — any integer from 1 to 31 (must be a valid day if a month is specified) mo nth — any integer from 1 to 12 (or the short name of the month such as jan or feb) d ay o f week — any integer from 0 to 7, where 0 or 7 represents Sunday (or the short name of the week such as sun or mon) The following define other job properties: username — specifies the user under which the jobs are run. co mmand — the command to be executed. The command can be either a command such as l s /pro c /tmp/pro c or a command which executes a custom script. For any of the above values, an asterisk (*) can be used to specify all valid values. If you, for example, define the month value as an asterisk, the job will be executed every month within the constraints of the other values. A hyphen (-) between integers specifies a range of integers. For example, 1-4 means the integers 1, 2, 3, and 4. A list of values separated by commas (,) specifies a list. For example, 3,4 ,6 ,8 indicates exactly these four integers. The forward slash (/) can be used to specify step values. The value of an integer will be skipped within a range following the range with /integer. For example, the minute value defined as 0 -59 /2 denotes every other minute in the minute field. Step values can also be used with an asterisk. For instance, if the month value is defined as */3, the task will run every third month. Any lines that begin with a hash sign (#) are comments and are not processed. Users other than ro o t can configure cron tasks with the cro ntab utility. The user-defined crontabs are stored in the /var/spo o l /cro n/ directory and executed as if run by the users that created them. To create a crontab as a specific user, login as that user and type the command cro ntab -e to edit the user's crontab with the editor specified in the VISUAL or ED IT O R environment variable. The file uses the same format as /etc/cro ntab. When the changes to the crontab are saved, the crontab is stored according to the user name and written to the file /var/spo o l /cro n/username. To list the contents of the current user's crontab file, use the cro ntab -l command. The /etc/cro n. d / directory contains files that have the same syntax as the /etc/cro ntab file. Only ro o t is allowed to create and modify files in this directory. 4 17 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note The cron daemon checks the /etc/anacro ntab file, the /etc/cro ntab file, the /etc/cro n. d / directory, and the /var/spo o l /cro n/ directory every minute for changes and the detected changes are loaded into memory. It is therefore not necessary to restart the daemon after an anacrontab or a crontab file have been changed. 21.1.5. Cont rolling Access t o Cron To restrict the access to Cron, you can use the /etc/cro n. al l o w and /etc/cro n. d eny files. These access control files use the same format with one user name on each line. Mind that no whitespace characters are permitted in either file. If the cro n. al l o w file exists, only users listed in the file are allowed to use cron, and the cro n. d eny file is ignored. If the cro n. al l o w file does not exist, users listed in the cro n. d eny file are not allowed to use Cron. The Cron daemon (cro nd ) does not have to be restarted if the access control files are modified. The access control files are checked each time a user tries to add or delete a cron job. The ro o t user can always use cron, regardless of the user names listed in the access control files. You can control the access also through Pluggable Authentication Modules (PAM). The settings are stored in the /etc/securi ty/access. co nf file. For example, after adding the following line to the file, no other user but the ro o t user can create crontabs: -:ALL EXCEPT root :cron The forbidden jobs are logged in an appropriate log file or, when using cro ntab -e, returned to the standard output. For more information, see the access. co nf. 5 manual page. 21.1.6. Black and Whit e List ing of Cron Jobs Black and white listing of jobs is used to define parts of a job that do not need to be executed. This is useful when calling the ru n - p art s script on a Cron directory, such as /etc/cro n. d ai l y/: if the user adds programs located in the directory to the job black list, the ru n - p art s script will not execute these programs. To define a black list, create a jo bs. d eny file in the directory that run-parts scripts will be executing from. For example, if you need to omit a particular program from /etc/cro n. d ai l y/, create the /etc/cro n. d ai l y/jo bs. d eny file. In this file, specify the names of the programs to be omitted from execution (only programs located in the same directory can be enlisted). If a job runs a command which runs the programs from the /etc/cro n. d ai l y/ directory, such as run-parts /etc/cro n. d ai l y, the programs defined in the jo bs. d eny file will not be executed. To define a white list, create a jo bs. al l o w file. The principles of jo bs. d eny and jo bs. al l o w are the same as those of cro n. d eny and cro n. al l o w described in section Section 21.1.5, “ Controlling Access to Cron” . 21.2. At and Bat ch While Cron is used to schedule recurring tasks, the At utility is used to schedule a one-time task at a 4 18 Chapt er 2 1 . Aut omat ing Syst em T asks specific time and the B at ch utility is used to schedule a one-time task to be executed when the system load average drops below 0.8. 21.2.1. Inst alling At and Bat ch To determine if the at package is already installed on your system, issue the following command: rpm -q at The command returns the full name of the at package if already installed or notifies you that the package is not available. To install the packages, use the yum command in the following form as ro o t: yum i nstal l package For example, to install both At and Batch, type the following at a shell prompt: ~]# yum i nstal l at For more information on how to install new packages in Red Hat Enterprise Linux, see Section 7.2.4, “ Installing Packages” . 21.2.2. Running t he At Service The At and Batch jobs are both picked by the atd service. This section provides information on how to start, stop, and restart the atd service, and shows how to configure it to start automatically at boot time. For more information on how to manage system services in Red Hat Enterprise Linux 7 in general, see Chapter 8, Managing Services with systemd. 2 1 .2 .2 .1 . St art ing and St o pping t he At Se rvice To determine if the service is running, use the following command: systemctl status atd . servi ce To run the atd service in the current session, type the following at a shell prompt as ro o t: systemctl start atd . servi ce To configure the service to start automatically at boot time, use the following command as ro o t: systemctl enabl e atd . servi ce Note It is recommended that you configure your system to start the atd service automatically at boot time. 2 1 .2 .2 .2 . St o pping t he At Se rvice 4 19 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide To stop the atd service, type the following at a shell prompt as ro o t: systemctl sto p atd . servi ce To prevent the service from starting automatically at boot time, use the following command as ro o t: systemctl d i sabl e atd . servi ce 2 1 .2 .2 .3. Re st art ing t he At Se rvice To restart the atd service, type the following at a shell prompt as ro o t: systemctl restart atd . servi ce This command stops the service and starts it again in quick succession. 21.2.3. Configuring an At Job To schedule a one-time job for a specific time with the At utility, do the following: 1. On the command line, type the command at TIME, where TIME is the time when the command is to be executed. The TIME argument can be defined in any of the following formats: HH: MM specifies the exact hour and minute; For example, 0 4 : 0 0 specifies 4:00 a.m. mi d ni g ht specifies 12:00 a.m. no o n specifies 12:00 p.m. teati me specifies 4:00 p.m. MONTHDAYYEAR format; For example, January 15 20 12 specifies the 15th day of January in the year 2012. The year value is optional. MMDDYY, MM/DD/YY, or MM. DD. YY formats; For example, 0 11512 for the 15th day of January in the year 2012. no w + TIME where TIME is defined as an integer and the value type: minutes, hours, days, or weeks. For example, no w + 5 d ays specifies that the command will be executed at the same time five days from now. The time must be specified first, followed by the optional date. For more information about the time format, see the /usr/share/d o c/at- /ti mespec text file. If the specified time has past, the job is executed at the time the next day. 2. In the displayed at> prompt, define the job commands: A. Type the command the job should execute and press Enter. Optionally, repeat the step to provide multiple commands. B. Enter a shell script at the prompt and press Enter after each line in the script. The job will use the shell set in the user's SHELL environment, the user's login shell, or /bi n/sh (whichever is found first). 4 20 Chapt er 2 1 . Aut omat ing Syst em T asks 3. Once finished, press C trl +D on an empty line to exit the prompt. If the set of commands or the script tries to display information to standard output, the output is emailed to the user. To view the list of pending jobs, use the atq command. See Section 21.2.5, “ Viewing Pending Jobs” for more information. You can also restrict the usage of the at command. For more information, see Section 21.2.7, “ Controlling Access to At and Batch” for details. 21.2.4 . Configuring a Bat ch Job The B at ch application executes the defined one-time tasks when the system load average decreases below 0.8. To define a Batch job, do the following: 1. On the command line, type the command batch. 2. In the displayed at> prompt, define the job commands: A. Type the command the job should execute and press Enter. Optionally, repeat the step to provide multiple commands. B. Enter a shell script at the prompt and press Enter after each line in the script. If a script is entered, the job uses the shell set in the user's SHELL environment, the user's login shell, or /bi n/sh (whichever is found first). 3. Once finished, press C trl +D on an empty line to exit the prompt. If the set of commands or the script tries to display information to standard output, the output is emailed to the user. To view the list of pending jobs, use the atq command. See Section 21.2.5, “ Viewing Pending Jobs” for more information. You can also restrict the usage of the batch command. For more information, see Section 21.2.7, “ Controlling Access to At and Batch” for details. 21.2.5. Viewing Pending Jobs To view the pending At and Batch jobs, run the atq command. The atq command displays a list of pending jobs, with each job on a separate line. Each line follows the job number, date, hour, job class, and user name format. Users can only view their own jobs. If the ro o t user executes the atq command, all jobs for all users are displayed. 21.2.6. Addit ional Command Line Opt ions Additional command line options for at and batch include the following: T ab le 21.1. at an d batch C o mman d Lin e O p t io n s O p t io n D escrip t io n -f Read the commands or shell script from a file instead of specifying them at the prompt. 4 21 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide O p t io n D escrip t io n -m -v Send email to the user when the job has been completed. D isplay the time that the job is executed. 21.2.7. Cont rolling Access t o At and Bat ch You can restrict the access to the at and batch commands using the /etc/at. al l o w and /etc/at. d eny files. These access control files use the same format defining one user name on each line. Mind that no whitespace are permitted in either file. If the file at. al l o w exists, only users listed in the file are allowed to use at or batch, and the at. d eny file is ignored. If at. al l o w does not exist, users listed in at. d eny are not allowed to use at or batch. The at daemon (atd ) does not have to be restarted if the access control files are modified. The access control files are read each time a user tries to execute the at or batch commands. The ro o t user can always execute at and batch commands, regardless of the content of the access control files. 21.3. Addit ional Resources To learn more about configuring automated tasks, see the following installed documentation: cro n(8) man page contains an overview of cron. cro ntab man pages in sections 1 and 5: The manual page in section 1 contains an overview of the cro ntab file. The man page in section 5 contains the format for the file and some example entries. anacro n(8) manual page contains an overview of anacron. anacro ntab(5) manual page contains an overview of the anacro ntab file. run-parts(4 ) manual page contains an overview of the run-parts script. /usr/share/d o c/at-version/ti mespec contains detailed information about the time values that can be used in cron job definitions. at manual page contains descriptions of at and batch and their command line options. 4 22 Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) Chapter 22. Automatic Bug Reporting Tool (ABRT) 22.1. Int roduct ion t o ABRT The Au t o mat ic B u g R ep o rt in g T o o l, commonly abbreviated as AB R T , is a set of tools that is designed to help users detect and report application crashes. Its main purpose is to ease the process of reporting issues and finding solutions. In this context, the solution can be a Bugzilla ticket, a knowledge-base article, or a suggestion to update a package to a version containing a fix. AB R T consists of the abrtd daemon and a number of system services and utilities for processing, analyzing, and reporting detected problems. The daemon runs silently in the background most of the time and springs into action when an application crashes or a kernel oops is detected. The daemon then collects the relevant problem data, such as a core file if there is one, the crashing application's command line parameters, and other data of forensic utility. AB R T currently supports the detection of crashes in applications written in the C, C++, Java, Python, and Ruby programming languages, as well as X.Org crashes, kernel oopses, and kernel panics. See Section 22.4, “ D etecting Software Problems” for more detailed information on the types of failures and crashes supported, and the way the various types of crashes are detected. The identified problems can be reported to a remote issue tracker, and the reporting can be configured to happen automatically whenever an issue is detected. Problem data can also be stored locally or on a dedicated system and reviewed, reported, and deleted manually by the user. The reporting tools can send problem data to a Bugzilla database or the Red Hat Technical Support (RHTSupport) website. The tools can also upload it using FT P or SC P , send it as an email, or write it to a file. The AB R T component that handles existing problem data (as opposed to, for example, the creation of new problem data) is a part of a separate project, lib rep o rt . The lib rep o rt library provides a generic mechanism for analyzing and reporting problems, and it is used by applications other than AB R T as well. However, AB R T and lib rep o rt operation and configuration are closely integrated. They are, therefore, discussed as one in this document. 22.2. Inst alling ABRT and St art ing it s Services In order to use AB R T , ensure that the abrt-desktop or the abrt-cli package is installed on your system. The abrt-desktop package provides a graphical user interface for AB R T , and the abrt-cli package contains a tool for using AB R T on the command line. You can also install both. The general workflow with both the AB R T GUI and the command line tool is procedurally similar and follows the same pattern. Warning Please note that installing the AB R T packages overwrites the /pro c/sys/kernel /co re_pattern file, which can contain a template used to name coredump files. The content of this file will be overwritten to: | /usr/libexec/abrt-hook-ccpp %s %c %p %u %g %t e See Section 7.2.4, “ Installing Packages” for general information on how to install packages using the Yu m package manager. 4 23 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 22.2.1. Inst alling t he ABRT GUI The AB R T graphical user interface provides an easy-to-use front end for working in a desktop environment. You can install the required package by running the following command as the ro o t user: ~]# yum i nstal l abrt-d eskto p Upon installation, the AB R T notification applet is configured to start automatically when your graphical desktop session starts. You can verify that the AB R T applet is running by issuing the following command in a terminal: ~]$ ps -el | g rep abrt-appl et 0 S 500 2036 1824 0 80 applet 0 - 61604 poll_s ? 00:00:00 abrt- If the applet is not running, you can start it manually in your current desktop session by running the abrt-appl et program: ~]$ abrt-appl et & [1] 2261 22.2.2. Inst alling ABRT for t he Command Line The command line interface is useful on headless machines, remote systems connected over a network, or in scripts. You can install the required package by running the following command as the ro o t user: ~]# yum i nstal l abrt-cl i 22.2.3. Inst alling Supplement ary ABRT T ools To receive email notifications about crashes detected by AB R T , you need to have the libreport-pluginmailx package installed. You can install it by executing the following command as ro o t: ~]# yum i nstal l l i brepo rt-pl ug i n-mai l x By default, it sends notifications to the ro o t user at the local machine. The email destination can be configured in the /etc/l i brepo rt/pl ug i ns/mai l x. co nf file. To have notifications displayed in your console at login time, install the abrt-console-notification package as well. AB R T can detect, analyze, and report various types of software failures. By default, AB R T is installed with support for the most common types of failures, such as crashes of C and C++ applications. Support for other types of failures is provided by independent packages. For example, to install support for detecting exceptions in applications written using the Java language, run the following command as ro o t: ~]# yum i nstal l abrt-java-co nnecto r 4 24 Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) See Section 22.4, “ D etecting Software Problems” for a list of languages and software projects which AB R T supports. The section also includes a list of all corresponding packages that enable the detection of the various types of failures. 22.2.4 . St art ing t he ABRT Services The abrtd daemon is configured to start at boot time. You can use the following command to verify its current status: ~]$ systemctl i s-acti ve abrtd . servi ce active If the systemctl command returns i nacti ve or unkno wn, the daemon is not running. You can start it for the current session by entering the following command as ro o t: ~]# systemctl start abrtd . servi ce Similarly, you can follow the same steps to check the status of and start the services that handle the various types of failures. For example, make sure the abrt-ccpp service is running if you want AB R T to detect C or C++ crashes. See Section 22.4, “ D etecting Software Problems” for a list of all available AB R T detection services and their respective packages. With the exception of the abrt-vmco re and abrt-psto reo o ps services, which are only started when a kernel panic or oops actually occurs, all AB R T services are automatically enabled and started at boot time when their respective packages are installed. You can disable or enable any AB R T service by using the systemctl utility as described in Chapter 8, Managing Services with systemd. 22.2.5. T est ing ABRT Crash Det ect ion To test that AB R T works properly, use the ki l l command to send the SEGV signal to terminate a process. For example, start a sl eep process and terminate it with the ki l l command in the following way: ~]$ sl eep 10 0 & [1] 2823 ~]$ ki l l -s SEG V 2823 AB R T detects a crash shortly after executing the ki l l command, and, provided a graphical session is running, the user is notified of the detected problem by the GUI notification applet. In the command line environment, you can check that the crash was detected by running the abrtcl i l i st command or by examining the crash dump created in the /var/tmp/abrt/ directory. See Section 22.5, “ Handling D etected Problems” for more information on how to work with detected crashes. 22.3. Configuring ABRT A problem life cycle is driven by events in AB R T . For example: Event #1 — a problem-data directory is created. Event #2 — problem data is analyzed. Event #3 — the problem is reported to Bugzilla. 4 25 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Whenever a problem is detected, AB R T compares it with all existing problem data and determines whether that same problem has already been recorded. If it has, the existing problem data is updated, and the most recent (duplicate) problem is not recorded again. If the problem is not recognized by AB R T , a p ro b lem- d at a d irect o ry is created. A problem-data directory typically consists of files such as: anal yzer, archi tecture, co red ump, cmd l i ne, executabl e, kernel , o s_rel ease, reaso n, ti me, and ui d . Other files, such as backtrace, can be created during the analysis of the problem, depending on which analyzer method is used and its configuration settings. Each of these files holds specific information about the system and the problem itself. For example, the kernel file records the version of a crashed kernel. After the problem-data directory is created and problem data gathered, you can process the problem using either the AB R T GUI, or the ab rt - cli utility for the command line. See Section 22.5, “ Handling D etected Problems” for more information about the AB R T tools provided for working with recorded problems. 22.3.1. Configuring Event s AB R T events use plugins to carry out the actual reporting operations. Plugins are compact utilities that the events call to process the content of problem-data directories. Using plugins, AB R T is capable of reporting problems to various destinations, and almost every reporting destination requires some configuration. For instance, Bugzilla requires a username, password, and a URL pointing to an instance of the Bugzilla service. Some configuration details can have default values (such as a Bugzilla URL), but others cannot have sensible defaults (for example, a username). AB R T looks for these settings in configuration files, such as repo rt_Bug zi l l a. co nf, in the /etc/l i brepo rt/events/ or $HO ME/. cache/abrt/events/ directories for system-wide or user-specific settings respectively. The configuration files contain pairs of directives and values. These files are the bare minimum necessary for running events and processing the problem-data directories. The g no me-abrt and abrt-cl i tools read the configuration data from these files and pass it to the events they run. Additional information about events (such as their description, names, types of parameters that can be passed to them as environment variables, and other properties) is stored in event_name. xml files in the /usr/share/l i brepo rt/events/ directory. These files are used by both g n o me- ab rt and ab rt - cli to make the user interface more friendly. D o not edit these files unless you want to modify the standard installation. If you intend to do that, copy the file to be modified to the /etc/l i brepo rt/events/ directory and modify the new file. These files can contain the following information: a user-friendly event name and description (Bugzilla, Report to Bugzilla bug tracker), a list of items in a problem-data directory that are required for the event to succeed, a default and mandatory selection of items to send or not send, whether the GUI should prompt for data review, what configuration options exist, their types (string, Boolean, etc.), default value, prompt string, etc.; this lets the GUI build appropriate configuration dialogs. For example, the repo rt_Lo g g er event accepts an output filename as a parameter. Using the respective event_name. xml file, the AB R T GUI determines which parameters can be specified for a selected event and allows the user to set the values for these parameters. The values are saved by the AB R T GUI and reused on subsequent invocations of these events. Note that the AB R T GUI 4 26 Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) saves configuration options using the G N O ME K eyrin g tool and by passing them to events, it overrides data from text configuration files. To open the graphical C o nfi g urati o n window, choose Au t o mat ic B u g R ep o rt in g T o o l → Pref eren ces from within a running instance of the g n o me- ab rt application. This window shows a list of events that can be selected during the reporting process when using the GUI. When you select one of the configurable events, you can click the C o nfi g ure button and modify the settings for that event. Fig u re 22.1. C o n f ig u rin g AB R T Even t s Important All files in the /etc/l i brepo rt/ directory hierarchy are world-readable and are meant to be used as global settings. Thus, it is not advisable to store usernames, passwords, or any other sensitive data in them. The per-user settings (set in the GUI application and readable by the owner of $HO ME only) are safely stored in G N O ME K eyrin g , or they can be stored in a text configuration file in $HO ME/. abrt/ for use with abrt-cl i . The following table shows a selection of the default analyzing, collecting, and reporting events provided by the standard installation of AB R T . The table lists each event's name, identifier, 4 27 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide configuration file from the /etc/l i brepo rt/events. d / directory, and a brief description. Note that while the configuration files use the event identifiers, the AB R T GUI refers to the individual events using their names. Note also that not all of the events can be set up using the GUI. For information on how to define a custom event, see Section 22.3.2, “ Creating Custom Events” . T ab le 22.1. St an d ard AB R T Even t s N ame Id en t if ier an d C o n f ig u rat io n File D escrip t io n uReport report_uReport Uploads a μReport to the FAF server. Mailx report_Mailx Sends the problem report via the Mailx utility to a specified email address. mai l x_event. co nf Bugzilla report_Bugzilla bug zi l l a_event. co nf Red Hat Customer Support report_RHTSupport Emergency analysis report_EmergencyAnalysis Analyze C or C++ Crash analyze_CCpp Report uploader report_Uploader rhtsuppo rt_event. co nf emerg encyanal ysi s_even t. co nf ccpp_event. co nf upl o ad er_event. co nf Analyze VM core analyze_VMcore vmco re_event. co nf Local GNU D ebugger analyze_LocalGD B Collect .xsessionerrors analyze_xsession_errors Logger report_Logger ccpp_event. co nf ccpp_event. co nf pri nt_event. co nf Kerneloops.org report_Kerneloops ko o ps_event. co nf 22.3.2. Creat ing Cust om Event s 4 28 Reports the problem to the specifid installation of the B u g z illa bug tracker. Reports the problem to the Red Hat Technical Support system. Uploads a tarball to the FAF server for further analysis. Used in case of a reporting failure when standard reporting methods fail. Sends the core dump to a remote retrace server for analysis or performs a local analysis if the remote one fails. Uploads a tarball (. tar. g z) archive with problem data to the chosen destination using the FT P or the SC P protocol. Runs the G D B (the GNU debugger) on the problem data of a kernel oops and generates a backtrace of the kernel. Runs G D B (the GNU debugger) on the problem data of an application and generates a backtrace of the program. Saves relevant lines from the ~ /. xsessi o nerro rs file to the problem report. Creates a problem report and saves it to a specified local file. Sends a kernel problem to the oops tracker at kerneloops.org. Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) 22.3.2. Creat ing Cust om Event s Each event is defined by one rule structure in a respective configuration file. The configuration files are typically stored in the /etc/l i brepo rt/events. d / directory. These configuration files are loaded by the main configuration file, /etc/l i brepo rt/repo rt_event. co nf. This file accepts shell metacharacters (*, $, ?, etc.) and interprets relative paths relatively to its location. Each rule starts with a line with a non-space leading character, and all subsequent lines starting with the space character or the tab character are considered a part of this rule. Each rule consists of two parts, a condition part and a program part. The condition part contains conditions in one of the following forms: VAR=VAL VAR!=VAL VAL~=REGEX where: VAR is either the EVENT key word or a name of a problem-data directory element (such as executabl e, packag e, ho stname, etc.), VAL is either a name of an event or a problem-data element, and REGEX is a regular expression. The program part consists of program names and shell-interpretable code. If all conditions in the condition part are valid, the program part is run in the shell. The following is an event example: E VENT=post-create date > /tmp/dt echo $HOSTNAME `uname -r` This event would overwrite the contents of the /tmp/d t file with the current date and time and print the hostname of the machine and its kernel version on the standard output. Here is an example of a more complex event, which is actually one of the predefined events. It saves relevant lines from the ~ /. xsessi o n-erro rs file to the problem report of any problem for which the abrt-ccpp service has been used, provided the crashed application had any X11 libraries loaded at the time of the crash: E VENT=analyze_xsession_errors analyzer=CCpp dso_list~=.*/libX11.* test -f ~/.xsession-errors || { echo "No ~/.xsession-errors"; exit 1; } test -r ~/.xsession-errors || { echo "Can't read ~/.xsessionerrors"; exit 1; } executable=`cat executable` & & base_executable=${executable##*/} & & grep -F -e "$base_executable" ~/.xsession-errors | tail -999 >xsession_errors & & echo "Element 'xsession_errors' saved" The set of possible events is not definitive. System administrators can add events according to their need. Currently, the following event names are provided with the standard AB R T and lib rep o rt installations: po st-create 4 29 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide This event is run by abrtd to process newly created problem-data directories. When the po st-create event is run, abrtd checks whether the i d of the new problem data matches the i d of any already existing problem directories. If such a problem directory exists, the new problem data is deleted. no ti fy, no ti fy-d up The no ti fy event is run following the completion of po st-create. When the event is run, the user can be sure that the problem deserves their attention. The no ti fy-d up is similar, except it is used for duplicate occurrences of the same problem. anal yze_name_suffix where name_suffix is the replaceable part of the event name. This event is used to process collected data. For example, the anal yze_Lo cal G D B event uses the GNU D ebugger (G D B ) utility to process the core dump of an application and produce a backtrace of the crash. co l l ect_name_suffix …where name_suffix is the adjustable part of the event name. This event is used to collect additional information on problems. repo rt_name_suffix …where name_suffix is the adjustable part of the event name. This event is used to report a problem. 22.3.3. Set t ing Up Aut omat ic Report ing AB R T can be configured to send initial anonymous reports, or μReports, of any detected issues or crashes automatically without any user interaction. When automatic reporting is turned on, the so called μReport, which is normally sent at the beginning of the crash-reporting process, is sent immediately after a crash is detected. This prevents duplicate support cases based on identical crashes. To enable the autoreporting feature, issue the following command as ro o t: ~]# abrt-auto -repo rti ng enabl ed The above command sets the Auto repo rti ng Enabl ed directive in the /etc/abrt/abrt. co nf configuration file to yes. This system-wide setting applies to all users of the system. Note that by enabling this option, automatic reporting will also be enabled in the graphical desktop environment. To only enable autoreporting in the AB R T GUI, switch the Auto mati cal l y send uR epo rt option to Y ES in the P ro bl em R epo rti ng C o nfi g urati o n window. To open this window, choose Au t o mat ic B u g R ep o rt in g T o o l → AB R T C o n f ig u rat io n from within a running instance of the g n o me- ab rt application. To launch the application, go to Ap p licat io n s → Su n d ry → Au t o mat ic B u g R ep o rt in g T o o l. 4 30 Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) Fig u re 22.2. C o n f ig u rin g AB R T Pro b lem R ep o rt in g Upon detection of a crash, by default, AB R T submits a μReport with basic information about the problem to Red Hat's AB R T server. The server determines whether the problem is known and either provides a short description of the problem along with a URL of the reported case if known, or invites the user to report it if not known. Note A μReport (microreport) is a JSON object representing a problem, such as a binary crash or a kernel oops. These reports are designed to be brief, machine readable, and completely anonymous, which is why they can be used for automated reporting. The μReports make it possible to keep track of bug occurrences, but they usually do not provide enough information for engineers to fix the bug. A full bug report is needed for a support case to be opened. To change the default behavior of the autoreporting facility from sending a μReport, modify the value of the Auto repo rti ng Event directive in the /etc/abrt/abrt. co nf configuration file to point to a different AB R T event. See Table 22.1, “ Standard ABRT Events” for an overview of the standard events. 4 31 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 22.4 . Det ect ing Soft ware Problems AB R T is capable of detecting, analyzing, and processing crashes in applications written in a variety of different programming languages. Many of the packages that contain the support for detecting the various types of crashes are installed automatically when either one of the main AB R T packages (abrt-desktop, abrt-cli) is installed. See Section 22.2, “ Installing ABRT and Starting its Services” for instructions on how to install AB R T . See the table below for a list of the supported types of crashes and the respective packages. T ab le 22.2. Su p p o rt ed Pro g rammin g Lan g u ag es an d So f t ware Pro ject s Lan g au g e/Pro ject Packag e C or C++ Python Ruby Java X.Org Linux (kernel oops) Linux (kernel panic) Linux (persistent storage) abrt-addon-ccpp abrt-addon-python rubygem-abrt abrt-java-connector abrt-addon-xorg abrt-addon-kerneloops abrt-addon-vmcore abrt-addon-pstoreoops 22.4 .1. Det ect ing C and C+ + Crashes The abrt-ccpp service installs its own core-dump handler, which, when started, overrides the default value of the kernel's co re_pattern variable, so that C and C++ crashes are handled by abrtd . If you stop the abrt-ccpp service, the previously specified value of co re_pattern is reinstated. By default, the /pro c/sys/kernel /co re_pattern file contains the string co re, which means that the kernel produces files with the co re. prefix in the current directory of the crashed process. The abrt-ccpp service overwrites the co re_pattern file to contain the following command: | /usr/libexec/abrt-hook-ccpp %s %c %p %u %g %t e This command instructs the kernel to pipe the core dump to the abrt-ho o k-ccpp program, which stores it in AB R T 's dump location and notifies the abrtd daemon of the new crash. It also stores the following files from the /pro c/PID/ directory (where PID is the ID of the crashed process) for debugging purposes: maps, l i mi ts, cg ro up, status. See proc(5) for a description of the format and the meaning of these files. 22.4 .2. Det ect ing Pyt hon Except ions The abrt-addon-python package installs a custom exception handler for Python applications. The Python interpreter then automatically imports the abrt. pth file installed in /usr/l i b6 4 /pytho n2. 7/si te-packag es/, which in turn imports abrt_excepti o n_hand l er. py. This overrides Python's default sys. exceptho o k with a custom handler, which forwards unhandled exceptions to abrtd via its Socket API. To disable the automatic import of site-specific modules, and thus prevent the AB R T custom exception handler from being used when running a Python application, pass the -S option to the Python interpreter: ~]$ pytho n -S file.py 4 32 Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) In the above command, replace file.py with the name of the Python script you want to execute without the use of site-specific modules. 22.4 .3. Det ect ing Ruby Except ions The rubygem-abrt package registers a custom handler using the at_exi t feature, which is executed when a program ends. This allows for checking for possible unhandled exceptions. Every time an unhandled exception is captured, the AB R T handler prepares a bug report, which can be submitted to Red Hat Bugzilla using standard AB R T tools. 22.4 .4 . Det ect ing Java Except ions The AB R T Java Connector is a JVM agent that reports uncaught Java exceptions to abrtd . The agent registers several JVMTI event callbacks and has to be loaded into the JVM using the ag entl i b command line parameter. Note that the processing of the registered callbacks negatively impacts the performance of the application. Use the following command to have AB R T catch exceptions from a Java class: ~]$ java -ag entl i b: abrt-java-co nnecto r[= abrt= o n] $MyClass pl atfo rm. jvmti Suppo rted true In the above command, replace $MyClass with the name of the Java class you want to test. By passing the abrt= o n option to the connector, you ensure that the exceptions are handled by abrtd . In case you want to have the connector output the exceptions to standard output, omit this option. 22.4 .5. Det ect ing X.Org Crashes The abrt-xo rg service collects and processes information about crashes of the X.O rg server from the /var/l o g /Xo rg . 0 . l o g file. Note that no report is generated if a blacklisted X.o rg module is loaded. Instead, a no t-repo rtabl e file is created in the problem-data directory with an appropriate explanation. You can find the list of offending modules in the /etc/abrt/pl ug i ns/xo rg . co nf file. Only proprietary graphics-driver modules are blacklisted by default. 22.4 .6. Det ect ing Kernel Oopses and Panics By checking the output of kernel logs, AB R T is able to catch and process the so-called kernel oopses — non-fatal deviations from the correct behavior of the Linux kernel. This functionality is provided by the abrt-o o ps service. AB R T can also detect and process kernel panics — fatal, non-recoverable errors that require a reboot, using the abrt-vmco re service. The service only starts when a vmco re file (a kernel-core dump) appears in the /var/crash/ directory. When a core-dump file is found, abrt-vmco re creates a new pro bl em-d ata d i recto ry in the /var/tmp/abrt/ directory and moves the coredump file to the newly created problem-data directory. After the /var/crash/ directory is searched, the service is stopped. For AB R T to be able to detect a kernel panic, the kd ump service must be enabled on the system. The amount of memory that is reserved for the kdump kernel has to be set correctly. You can set it using the syst em- co n f ig - kd u mp graphical tool or by specifying the crashkernel parameter in the list of kernel options in the /etc/d efaul t/g rub configuration file. For details on how to enable and configure kd ump, see the Red Hat Enterprise Linux 7 Kernel Crash D ump Guide. Using the abrt-psto reo o ps service, AB R T is capable of collecting and processing information about kernel panics, which, on systems that support pstore, is stored in the automatically-mounted 4 33 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide /sys/fs/psto re/ directory. The platform-dependent pstore interface (persistent storage) provides a mechanism for storing data across system reboots, thus allowing for preserving kernel panic information. The service starts automatically when kernel crash-dump files appear in the /sys/fs/psto re/ directory. 22.5. Handling Det ect ed Problems Problem data saved by abrtd can be viewed, reported, and deleted using either the command line tool, abrt-cl i , or the graphical tool, g no me-abrt. Note Note that AB R T identifies duplicate problems by comparing new problems with all locally saved problems. For a repeating crash, AB R T requires you to act upon it only once. However, if you delete the crash dump of that problem, the next time this specific problem occurs, AB R T will treat it as a new crash: AB R T will alert you about it, prompt you to fill in a description, and report it. To avoid having AB R T notifying you about a recurring problem, do not delete its problem data. 22.5.1. Using t he Command Line T ool In the command line environment, the user is notified of new crashes on login, provided they have the abrt-console-notification package installed. The console notification looks like the following: ABRT has detected 1 problem(s). For more info run: abrt-cli list --since 1398783164 To view detected problems, enter the abrt-cl i l i st command: ~]$ abrt-cl i l i st id 6734c6f1a1ed169500a7bfc8bd62aabaf039f9aa Directory: /var/tmp/abrt/ccpp-2014-04-21-09:47:51-3430 count: 1 executable: /usr/bin/sleep package: coreutils-8.22-11.el7 time: Mon 21 Apr 2014 09:47:51 AM EDT uid: 1000 Run 'abrt-cli report /var/tmp/abrt/ccpp-2014-04-21-09:47:51-3430' for creating a case in Red Hat Customer Portal Each crash listed in the output of the abrt-cl i l i st command has a unique identifier and a directory that can be used for further manipulation using abrt-cl i . To view information about just one particular problem, use the abrt-cl i i nfo command: abrt-cl i i nfo [-d ] directory_or_id To increase the amount of information displayed when using both the l i st and i nfo subcommands, pass them the -d (--d etai l ed ) option, which shows all stored information about the problems listed, including respective backtrace files if they have already been generated. To analyze and report a certain problem, use the abrt-cl i repo rt command: 4 34 Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) abrt-cl i repo rt directory_or_id Upon invocation of the above command, you will be asked to provide your credentials for opening a support case with Red Hat Customer Support. Next, abrt-cl i opens a text editor with the content of the report. You can see what is being reported, and you can fill in instructions on how to reproduce the crash and other comments. You should also check the backtrace because the backtrace might be sent to a public server and viewed by anyone, depending on the problem-reporter event settings. Note You can choose which text editor is used to check the reports. abrt-cl i uses the editor defined in the ABR T _ED IT O R environment variable. If the variable is not defined, it checks the VISUAL and ED IT O R variables. If none of these variables is set, the vi editor is used. You can set the preferred editor in your . bashrc configuration file. For example, if you prefer G N U Emacs, add the following line to the file: export VISUAL=emacs When you are done with the report, save your changes and close the editor. If you have reported your problem to the Red Hat Customer Support database, a problem case is filed in the database. From now on, you will be informed about the problem-resolution progress via email you provided during the process of reporting. You can also monitor the problem case using the URL that is provided to you when the problem case is created or via emails received from Red Hat Support. If you are certain that you do not want to report a particular problem, you can delete it. To delete a problem, so that AB R T does not keep information about it, use the command: abrt-cl i rm directory_or_id To display help about a particular abrt-cl i command, use the --hel p option: abrt-cl i command --hel p 22.5.2. Using t he GUI The AB R T daemon broadcasts a D -Bus message whenever a problem report is created. If the AB R T applet is running in a graphical desktop environment, it catches this message and displays a notification dialog on the desktop. You can open the AB R T GUI using this dialog by clicking on the R epo rt button. You can also open the AB R T GUI by selecting the Ap p licat io n s → Su n d ry → Au t o mat ic B u g R ep o rt in g T o o l menu item. Alternatively, you can run the AB R T GUI from the command line as follows: ~]$ g no me-abrt & The AB R T GUI window displays a list of detected problems. Each problem entry consists of the name of the failing application, the reason why the application crashed, and the date of the last occurrence of the problem. 4 35 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 22.3. AB R T G U I To access a detailed problem description, double-click on a problem-report line or click on the R epo rt button while the respective problem line is selected. You can then follow the instructions to proceed with the process of describing the problem, determining how it should be analyzed, and where it should be reported. To discard a problem, click on the D el ete button. 22.6. Addit ional Resources For more information about AB R T and related topics, see the resources listed below. Inst alled Document at ion abrtd(8) — The manual page for the abrtd daemon provides information about options that can be used with the daemon. abrt_event.conf(5) — The manual page for the abrt_event. co nf configuration file describes the format of its directives and rules and provides reference information about event meta-data configuration in XML files. Online Document at ion 4 36 Chapt er 2 2 . Aut omat ic Bug Report ing T ool (ABRT ) Red Hat Enterprise Linux 7 Networking Guide — The Networking Guide for Red Hat Enterprise Linux 7 documents relevant information regarding the configuration and administration of network interfaces and network services on this system. Red Hat Enterprise Linux 7 Kernel Crash D ump Guide — The Kernel Crash Dump Guide for Red Hat Enterprise Linux 7 documents how to configure, test, and use the kd ump crash recovery service and provides a brief overview of how to analyze the resulting core dump using the crash debugging utility. See Also Chapter 20, Viewing and Managing Log Files describes the configuration of the rsysl o g daemon and the systemd journal and explains how to locate, view, and monitor system logs. Chapter 7, Yum describes how to use the Yu m package manager to search, install, update, and uninstall packages on the command line. Chapter 8, Managing Services with systemd provides an introduction to systemd and documents how to use the systemctl command to manage system services, configure systemd targets, and execute power management commands. 4 37 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 23. OProfile OProfile is a low overhead, system-wide performance monitoring tool. It uses the performance monitoring hardware on the processor to retrieve information about the kernel and executables on the system, such as when memory is referenced, the number of L2 cache requests, and the number of hardware interrupts received. On a Red Hat Enterprise Linux system, the o pro fi l e package must be installed to use this tool. Many processors include dedicated performance monitoring hardware. This hardware makes it possible to detect when certain events happen (such as the requested data not being in cache). The hardware normally takes the form of one or more counters that are incremented each time an event takes place. When the counter value increments, an interrupt is generated, making it possible to control the amount of detail (and therefore, overhead) produced by performance monitoring. OProfile uses this hardware (or a timer-based substitute in cases where performance monitoring hardware is not present) to collect samples of performance-related data each time a counter generates an interrupt. These samples are periodically written out to disk; later, the data contained in these samples can then be used to generate reports on system-level and application-level performance. Be aware of the following limitations when using OProfile: Use of shared libraries — Samples for code in shared libraries are not attributed to the particular application unless the --separate= l i brary option is used. Performance monitoring samples are inexact — When a performance monitoring register triggers a sample, the interrupt handling is not precise like a divide by zero exception. D ue to the out-oforder execution of instructions by the processor, the sample may be recorded on a nearby instruction. opreport does not associate samples for inline functions properly — o prepo rt uses a simple address range mechanism to determine which function an address is in. Inline function samples are not attributed to the inline function but rather to the function the inline function was inserted into. OProfile accumulates data from multiple runs — OProfile is a system-wide profiler and expects processes to start up and shut down multiple times. Thus, samples from multiple runs accumulate. Use the command o pco ntro l --reset to clear out the samples from previous runs. Hardware performance counters do not work on guest virtual machines — Because the hardware performance counters are not available on virtual systems, you need to use the ti mer mode. Enter the command o pco ntro l --d ei ni t, and then execute mo d pro be o pro fi l e ti mer= 1 to enable the ti mer mode. Non-CPU-limited performance problems — OProfile is oriented to finding problems with CPU-limited processes. OProfile does not identify processes that are asleep because they are waiting on locks or for some other event to occur (for example an I/O device to finish an operation). 23.1. Overview of T ools Table 23.1, “ OProfile Commands” provides a brief overview of the most commonly used tools provided with the o pro fi l e package. T ab le 23.1. O Pro f ile C o mman d s 4 38 Chapt er 2 3. O Profile C o mman d D escrip t io n o phel p D isplays available events for the system's processor along with a brief description of each. Converts sample database files from a foreign binary format to the native format for the system. Only use this option when analyzing a sample database from a different architecture. Creates annotated source for an executable if the application was compiled with debugging symbols. See Section 23.6.4, “ Using o panno tate” for details. Configures what data is collected. See Section 23.3, “ Configuring OProfile Using Legacy Mode” for details. Recommended tool to be used in place of o pco ntro l for profiling. See Section 23.2, “ Using operf” for details. For differences between o perf and o pco ntro l see Section 23.1.1, “ operf vs. opcontrol” . Retrieves profile data. See Section 23.6.1, “ Using o prepo rt” for details. Runs as a daemon to periodically write sample data to disk. o pi mpo rt o panno tate o pco ntro l o perf o prepo rt o pro fi l ed 23.1.1. operf vs. opcont rol There are two mutually exclusive methods for collecting profiling data with OProfile. You can either use the newer and preferred o perf or the o pco ntro l tool. o pe rf This is the recommended mode for profiling. The o perf tool uses the Linux Performance Events Subsystem, and therefore does not require the oprofile kernel driver. The o perf tool allows you to target your profiling more precisely, as a single process or system-wide, and also allows OProfile to co-exist better with other tools using the performance monitoring hardware on your system. Unlike o pco ntro l , it can be used without the ro o t privileges. However, o perf is also capable of systemwide operations with use of the --system-wi d e option, where root authority is required. With o perf, there is no initial setup needed. You can invoke o perf with command-line options to specify your profiling settings. After that, you can run the OProfile post-processing tools described in Section 23.6, “ Analyzing the D ata” . See Section 23.2, “ Using operf” for further information. o pco nt ro l This mode consists of the o pco ntro l shell script, the o pro fi l ed daemon, and several postprocessing tools. The o pco ntro l command is used for configuring, starting, and stopping a profiling session. An OProfile kernel driver, usually built as a kernel module, is used for collecting samples, which are then recorded into sample files by o pro fi l ed . You can use legacy mode only if you have ro o t privileges. In certain cases, such as when you need to sample areas with disabled interrupt request (IRQ), this is a better alternative. Before OProfile can be run in legacy mode, it must be configured as shown in Section 23.3, “ Configuring OProfile Using Legacy Mode” . These settings are then applied when starting OProfile (Section 23.4, “ Starting and Stopping OProfile Using Legacy Mode” ). 23.2. Using operf 4 39 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide o perf is the recommended profiling mode that does not require initial setup before starting. All settings are specified as command-line options and there is no separate command to start the profiling process. To stop o perf, press Ctrl+C. The typical o perf command syntax looks as follows: o perf options range command args Replace options with the desired command-line options to specify your profiling settings. Full set of options is described in o perf(1) manual page. Replace range with one of the following: --system-wi d e - this setting allows for global profiling, see Using o perf in System-wide Mode --pi d = PID - this is to profile a running application, where PID is the process ID of the process you want to profile. With command and args, you can define a specific command or application to be profiled, and also the input arguments that this command or application requires. Either command, --pi d or -system-wi d e is required, but these cannot be used simultaneously. When you invoke o perf on a command line without setting the range option, data will be collected for the children processes. Using o perf in System-wide Mode To run o perf --system-wi d e, you need ro o t authority. When finished profiling, you can stop o perf with C trl + C . If you run o perf --system-wi d e as a background process (with & ), stop it in a controlled manner in order to process the collected profile data. For this purpose, use: ki l l -SIG INT o perf-P ID When running o perf --system-wi d e, it is recommended that your current working directory is /ro o t or a subdirectory of /ro o t so that sample data files are not stored in locations accessible by regular users. 23.2.1. Specifying t he Kernel To monitor the kernel, execute the following command: o perf --vml i nux=vmlinux_path With this option, you can specify a path to a vmlinux file that matches the running kernel. Kernel samples will be attributed to this binary, allowing post-processing tools to attribute samples to the appropriate kernel symbols. If this option is not specified, all kernel samples will be attributed to a pseudo binary named " no-vmlinux" . 23.2.2. Set t ing Event s t o Monit or Most processors contain counters, which are used by OProfile to monitor specific events. As shown in Table 23.3, “ OProfile Processors and Counters” , the number of counters available depends on the processor. 440 Chapt er 2 3. O Profile The events for each counter can be configured via the command line or with a graphical interface. For more information on the graphical interface, see Section 23.10, “ Graphical Interface” . If the counter cannot be set to a specific event, an error message is displayed. Note Some older processor models are not supported by the underlying Linux Performance Events Subsystem kernel and therefore are not supported by o perf. If you receive this message: Your kernel's Performance Events Subsystem does not support your processor type when attempting to use o perf, try profiling with o pco ntro l to see if your processor type may be supported by OProfile's legacy mode. Note Since hardware performance counters are not available on guest virtual machines, you have to enable timer mode to use o p erf on virtual systems. To do so, type as ro o t: o pco ntro l --d ei ni t mo d pro be o pro fi l e ti mer= 1 To set the event for each configurable counter via the command line, use: o perf --events=event1,event2… Here, pass a comma-separated list of event specifications for profiling. Each event specification is a colon-separated list of attributes in the following form: event-name:sample-rate:unit-mask:kernel:user Table 23.2, “ Event Specifications” summarizes these options. The last three values are optional, if you omit them, they will be set to their default values. Note that certain events do require a unit mask. T ab le 23.2. Even t Sp ecif icat io n s Sp ecif icat io n D escrip t io n event-name The exact symbolic event name taken from o phel p 441 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Sp ecif icat io n D escrip t io n sample-rate The number of events to wait before sampling again. The smaller the count, the more frequent the samples. For events that do not happen frequently, a lower count may be needed to capture a statistically significant number of event instances. On the other hand, sampling too frequently can overload the system. By default, OProfile uses a time-based event set, which creates a sample every 100,000 clock cycles per processor. Unit masks, which further define the event, are listed in o phel p. You can insert either a hexadecimal value, beginning with " 0x" , or a string that matches the first word of the unit mask description in o phel p. D efinition by name is valid only for unit masks having " extra:" parameters, as shown by the output of o phel p. This type of unit mask cannot be defined with a hexadecimal value. Note that on certain architectures, there can be multiple unit masks with the same hexadecimal value. In that case they have to be specified by their names only. Specifies whether to profile kernel code (insert 0 or 1(default)) Specifies whether to profile user-space code (insert 0 or 1 (default)) unit-mask kernel user The events available vary depending on the processor type. When no event specification is given, the default event for the running processor type will be used for profiling. See Table 23.4, “ D efault Events” for a list of these default events. To determine the events available for profiling, use the o phel p command. o phel p 23.2.3. Cat egoriz at ion of Samples The --separate-thread option categorizes samples by thread group ID (tgid) and thread ID (tid). This is useful for seeing per-thread samples in multi-threaded applications. When used in conjunction with the --system-wi d e option, --separate-thread is also useful for seeing perprocess (i.e., per-thread group) samples for the case where multiple processes are executing the same program during a profiling run. The --separate-cpu option categorizes samples by CPU. 23.3. Configuring OProfile Using Legacy Mode Before OProfile can be run in legacy mode, it must be configured. At a minimum, selecting to monitor the kernel (or selecting not to monitor the kernel) is required. The following sections describe how to use the o pco ntro l utility to configure OProfile. As the o pco ntro l commands are executed, the setup options are saved to the /ro o t/. o pro fi l e/d aemo nrc file. 23.3.1. Specifying t he Kernel 442 Chapt er 2 3. O Profile First, configure whether OProfile should monitor the kernel. This is the only configuration option that is required before starting OProfile. All others are optional. To monitor the kernel, execute the following command as ro o t: o pco ntro l --setup --vml i nux= /usr/l i b/d ebug /l i b/mo d ul es/`uname r`/vml i nux Install the debuginfo package In order to monitor the kernel, the kernel-debuginfo package which contains the uncompressed kernel must be installed. For more information on how to install this package, see the How to download debuginfo packages like kernel-debuginfo? article on the Red Hat Customer Portal. To configure OProfile not to monitor the kernel, execute the following command as ro o t: o pco ntro l --setup --no -vml i nux This command also loads the o pro fi l e kernel module, if it is not already loaded, and creates the /d ev/o pro fi l e/ directory, if it does not already exist. See Section 23.7, “ Understanding the /dev/oprofile/ directory” for details about this directory. Setting whether samples should be collected within the kernel only changes what data is collected, not how or where the collected data is stored. To generate different sample files for the kernel and application libraries, see Section 23.3.3, “ Separating Kernel and User-space Profiles” . 23.3.2. Set t ing Event s t o Monit or Most processors contain counters, which are used by OProfile to monitor specific events. As shown in Table 23.3, “ OProfile Processors and Counters” , the number of counters available depends on the processor. T ab le 23.3. O Pro f ile Pro cesso rs an d C o u n t ers Pro cesso r cpu_type N u mb er o f C o u n t ers AMD 64 AMD Family 10h AMD Family 11h AMD Family 12h AMD Family 14h AMD Family 15h Applied Micro X-Gene ARM Cortex A53 ARM Cortex A57 IBM eServer System i and IBM eServer System p IBM POWER4 IBM POWER5 IBM PowerPC 970 IBM PowerPC 970MP x86-64/hammer x86-64/family10 x86-64/family11 x86-64/family12 x86-64/family14 x86-64/family15 arm/armv8-xgene arm/armv8-ca53 arm/armv8-ca57 timer 4 4 4 4 4 6 4 6 6 1 ppc64/power4 ppc64/power5 ppc64/970 ppc64/970MP 8 6 8 8 443 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Pro cesso r cpu_type N u mb er o f C o u n t ers IBM POWER5+ IBM POWER5++ IBM POWER56 IBM POWER7 IBM POWER8 IBM S/390 and IBM System z Intel Core i7 Intel Nehalem microarchitecture Intel Westmere microarchitecture Intel Haswell microarchitecture (nonhyper-threaded) Intel Haswell microarchitecture (hyperthreaded) Intel Ivy Bridge microarchitecture (nonhyper-threaded) Intel Ivy Bridge microarchitecture (hyperthreaded) Intel Sandy Bridge microarchitecture (non-hyper-threaded) Intel Sandy Bridge microarchitecture Intel Broadwell microarchitecture (nonhyper-threaded) Intel Broadwell microarchitecture (hyperthreaded) Intel Silvermont microarchitecture TIMER_INT ppc64/power5+ ppc64/power5++ ppc64/power6 ppc64/power7 ppc64/power7 timer i386/core_i7 i386/nehalem i386/westmere i386/haswell 6 6 6 6 8 1 4 4 4 8 i386/haswell-ht 4 i386/ivybridge 8 i386/ivybridge-ht 4 i386/sandybridge 8 i386/sandybridge-ht i386/broadwell 4 8 i386/broadwell-ht 4 i386/silvermont timer 2 1 Use Table 23.3, “ OProfile Processors and Counters” to determine the number of events that can be monitored simultaneously for your CPU type. If the processor does not have supported performance monitoring hardware, the ti mer is used as the processor type. If ti mer is used, events cannot be set for any processor because the hardware does not have support for hardware performance counters. Instead, the timer interrupt is used for profiling. If ti mer is not used as the processor type, the events monitored can be changed, and counter 0 for the processor is set to a time-based event by default. If more than one counter exists on the processor, the counters other than 0 are not set to an event by default. The default events monitored are shown in Table 23.4, “ D efault Events” . T ab le 23.4 . D ef au lt Even t s Pro cesso r D ef au lt Even t f o r C o u n t er D escrip t io n AMD Athlon and AMD 64 AMD Family 10h, AMD Family 11h, AMD Family 12h AMD Family 14h, AMD Family 15h Applied Micro X-Gene ARM Cortex A53 CPU_CLK_UNHALTED The processor's clock is not halted CPU_CLK_UNHALTED The processor's clock is not halted CPU_CLK_UNHALTED The processor's clock is not halted CPU_CYCLES CPU_CYCLES Processor Cycles Processor Cycles 444 Chapt er 2 3. O Profile Pro cesso r D ef au lt Even t f o r C o u n t er D escrip t io n ARM Cortex A57 IBM POWER4 IBM POWER5 IBM POWER8 IBM PowerPC 970 Intel Core i7 Intel Nehalem microarchitecture Intel Pentium 4 (hyperthreaded and nonhyper-threaded) Intel Westmere microarchitecture Intel Broadwell microarchitecture Intel Silvermont microarchitecture TIMER_INT CPU_CYCLES CYCLES CYCLES CYCLES CYCLES CPU_CLK_UNHALTED CPU_CLK_UNHALTED Processor Cycles Processor Cycles Processor Cycles Processor Cycles Processor Cycles The processor's clock is not halted The processor's clock is not halted GLOBAL_POWER_EVENTS The time during which the processor is not stopped CPU_CLK_UNHALTED The processor's clock is not halted CPU_CLK_UNHALTED The processor's clock is not halted CPU_CLK_UNHALTED The processor's clock is not halted (none) Sample for each timer interrupt The number of events that can be monitored at one time is determined by the number of counters for the processor. However, it is not a one-to-one correlation; on some processors, certain events must be mapped to specific counters. To determine the number of counters available, execute the following command: l s -d /d ev/o pro fi l e/[0 -9 ]* The events available vary depending on the processor type. Use the o phel p command to determine the events available for profiling. The list is specific to the system's processor type. o phel p Note Unless OProfile is properly configured, o phel p fails with the following error message: Unable to open cpu_type file for reading Make sure you have done opcontrol --init cpu_type 'unset' is not valid you should upgrade oprofile or force the use of timer mode To configure OProfile, follow the instructions in Section 23.3, “ Configuring OProfile Using Legacy Mode” . The events for each counter can be configured via the command line or with a graphical interface. For more information on the graphical interface, see Section 23.10, “ Graphical Interface” . If the counter cannot be set to a specific event, an error message is displayed. To set the event for each configurable counter via the command line, use o pco ntro l : 445 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide o pco ntro l --event= event-name: sample-rate Replace event-name with the exact name of the event from o phel p, and replace sample-rate with the number of events between samples. 2 3.3.2 .1 . Sam pling Rat e By default, a time-based event set is selected. It creates a sample every 100,000 clock cycles per processor. If the timer interrupt is used, the timer is set to the respective rate and is not user-settable. If the cpu_type is not ti mer, each event can have a sampling rate set for it. The sampling rate is the number of events between each sample snapshot. When setting the event for the counter, a sample rate can also be specified: o pco ntro l --event= event-name: sample-rate Replace sample-rate with the number of events to wait before sampling again. The smaller the count, the more frequent the samples. For events that do not happen frequently, a lower count may be needed to capture the event instances. Sampling too frequently can overload the system Be extremely careful when setting sampling rates. Sampling too frequently can overload the system, causing the system to appear frozen or causing the system to actually freeze. 2 3.3.2 .2 . Unit Masks Some user performance monitoring events may also require unit masks to further define the event. Unit masks for each event are listed with the o phel p command. The values for each unit mask are listed in hexadecimal format. To specify more than one unit mask, the hexadecimal values must be combined using a bitwise or operation. o pco ntro l --event= event-name: sample-rate: unit-mask Note that on certain architectures, there can be multiple unit masks with the same hexadecimal value. In that case they have to be specified by their names only. 23.3.3. Separat ing Kernel and User-space Profiles By default, kernel mode and user mode information is gathered for each event. To configure OProfile to ignore events in kernel mode for a specific counter, execute the following command: o pco ntro l --event= event-name: sample-rate: unit-mask: 0 Execute the following command to start profiling kernel mode for the counter again: o pco ntro l --event= event-name: sample-rate: unit-mask: 1 To configure OProfile to ignore events in user mode for a specific counter, execute the following command: 446 Chapt er 2 3. O Profile o pco ntro l --event= event-name: sample-rate: unit-mask: 1: 0 Execute the following command to start profiling user mode for the counter again: o pco ntro l --event= event-name: sample-rate: unit-mask: 1: 1 When the OProfile daemon writes the profile data to sample files, it can separate the kernel and library profile data into separate sample files. To configure how the daemon writes to sample files, execute the following command as root: o pco ntro l --separate= choice The choice argument can be one of the following: no ne — D o not separate the profiles (default). l i brary — Generate per-application profiles for libraries. kernel — Generate per-application profiles for the kernel and kernel modules. al l — Generate per-application profiles for libraries and per-application profiles for the kernel and kernel modules. If --separate= l i brary is used, the sample file name includes the name of the executable as well as the name of the library. Note These configuration changes will take effect when the OProfile profiler is restarted. 23.4 . St art ing and St opping OProfile Using Legacy Mode To start monitoring the system with OProfile, execute the following command as root: o pco ntro l --start Output similar to the following is displayed: Using log file /var/lib/oprofile/oprofiled.log Daemon started. Profiler running. The settings in /ro o t/. o pro fi l e/d aemo nrc are used. The OProfile daemon, o pro fi l ed , is started; it periodically writes the sample data to the /var/l i b/o pro fi l e/sampl es/ directory. The log file for the daemon is located at /var/l i b/o pro fi l e/o pro fi l ed . l o g . 447 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Disable the nmi_watchdog registers On a Red Hat Enterprise Linux 7 system, the nmi _watchd o g registers with the perf subsystem. D ue to this, the perf subsystem grabs control of the performance counter registers at boot time, blocking OProfile from working. To resolve this, either boot with the nmi _watchd o g = 0 kernel parameter set, or run the following command as ro o t to disable nmi _watchd o g at run time: echo 0 > /pro c/sys/kernel /nmi _watchd o g To re-enable nmi _watchd o g , use the following command as ro o t: echo 1 > /pro c/sys/kernel /nmi _watchd o g To stop the profiler, execute the following command as root: o pco ntro l --shutd o wn 23.5. Saving Dat a in Legacy Mode Sometimes it is useful to save samples at a specific time. For example, when profiling an executable, it may be useful to gather different samples based on different input data sets. If the number of events to be monitored exceeds the number of counters available for the processor, multiple runs of OProfile can be used to collect data, saving the sample data to different files each time. To save the current set of sample files, execute the following command, replacing name with a unique descriptive name for the current session: o pco ntro l --save= name The command creates the directory /var/l i b/o pro fi l e/sampl es/name/ and the current sample files are copied to it. To specify the session directory to hold the sample data, use the --sessi o n-d i r option. If not specified, the data is saved in the o pro fi l e_d ata/ directory on the current path. 23.6. Analyz ing t he Dat a The same OProfile post-processing tools are used whether you collect your profile with o perf or o pco ntro l in legacy mode. By default, o perf stores the profiling data in the current_dir/o pro fi l e_d ata/ directory. You can change to a different location with the --sessi o n-d i r option. The usual post-profiling analysis tools such as o prepo rt and o panno tate can be used to generate profile reports. These tools search for samples in current_dir/o pro fi l e_d ata/ first. If this directory does not exist, the analysis tools use the standard session directory of /var/l i b/o pro fi l e/. Statistics, such as total samples received and lost samples, are written to the session_dir/sampl es/o perf. l o g file. 448 Chapt er 2 3. O Profile When using legacy mode, the OProfile daemon, o pro fi l ed , periodically collects the samples and writes them to the /var/l i b/o pro fi l e/sampl es/ directory. Before reading the data, make sure all data has been written to this directory by executing the following command as root: o pco ntro l --d ump Each sample file name is based on the name of the executable. For example, the samples for the default event on a Pentium III processor for /bi n/bash becomes: \{root\}/bin/bash/\{dep\}/\{root\}/bin/bash/CPU_CLK_UNHALTED.100000 The following tools are available to profile the sample data once it has been collected: o prepo rt o panno tate Use these tools, along with the binaries profiled, to generate reports that can be further analyzed. Back up the executable and the sample files The executable being profiled must be used with these tools to analyze the data. If it must change after the data is collected, back up the executable used to create the samples as well as the sample files. Note that the names of the sample file and the binary have to agree. You cannot make a backup if these names do not match. As an alternative, o parchi ve can be used to address this problem. Samples for each executable are written to a single sample file. Samples from each dynamically linked library are also written to a single sample file. While OProfile is running, if the executable being monitored changes and a sample file for the executable exists, the existing sample file is automatically deleted. Thus, if the existing sample file is needed, it must be backed up, along with the executable used to create it before replacing the executable with a new version. The OProfile analysis tools use the executable file that created the samples during analysis. If the executable changes, the analysis tools will be unable to analyze the associated samples. See Section 23.5, “ Saving D ata in Legacy Mode” for details on how to back up the sample file. 23.6.1. Using o prepo rt The o prepo rt tool provides an overview of all the executables being profiled. The following is part of a sample output from the o prepo rt command: ~]$ o prepo rt Profiling through timer interrupt TIMER:0| samples| %| -----------------25926 97.5212 no-vmlinux 359 1.3504 pi 65 0.2445 Xorg 62 0.2332 libvte.so.4.4.0 56 0.2106 libc-2.3.4.so 34 0.1279 libglib-2.0.so.0.400.7 19 0.0715 libXft.so.2.1.2 449 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 17 8 8 6 5 4 4 3 3 1 1 1 1 1 1 0.0639 bash 0.0301 ld-2.3.4.so 0.0301 libgdk-x11-2.0.so.0.400.13 0.0226 libgobject-2.0.so.0.400.7 0.0188 oprofiled 0.0150 libpthread-2.3.4.so 0.0150 libgtk-x11-2.0.so.0.400.13 0.0113 libXrender.so.1.2.2 0.0113 du 0.0038 libcrypto.so.0.9.7a 0.0038 libpam.so.0.77 0.0038 libtermcap.so.2.0.8 0.0038 libX11.so.6.2 0.0038 libgthread-2.0.so.0.400.7 0.0038 libwnck-1.so.4.9.0 Each executable is listed on its own line. The first column is the number of samples recorded for the executable. The second column is the percentage of samples relative to the total number of samples. The third column is the name of the executable. See the o prepo rt(1) manual page for a list of available command-line options, such as the -r option used to sort the output from the executable with the smallest number of samples to the one with the largest number of samples. You can also use the -t or --thresho l d option to trim the output of o pco ntro l . 23.6.2. Using opreport on a Single Execut able To retrieve more detailed profiled information about a specific executable, use: o prepo rt mode executable Replace executable with the full path to the executable to be analyzed. mode stands for one of the following options: -l This option is used to list sample data by symbols. For example, running this command: ~]# o prepo rt -l /l i b/tl s/l i bc-version. so produces the following output: samples % symbol name 12 21.4286 __gconv_transform_utf8_internal 5 8.9286 _int_malloc 4 7.1429 malloc 3 5.3571 __i686.get_pc_thunk.bx 3 5.3571 _dl_mcount_wrapper_check 3 5.3571 mbrtowc 3 5.3571 memcpy 2 3.5714 _int_realloc 2 3.5714 _nl_intern_locale_data 2 3.5714 free 2 3.5714 strcmp 1 1.7857 __ctype_get_mb_cur_max 1 1.7857 __unregister_atfork 4 50 Chapt er 2 3. O Profile 1 1 1 1 1 1 1 1 1 1 1 1 1 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 1.7857 __write_nocancel _dl_addr _int_free _itoa_word calc_eclosure_iter fopen@ @ GLIBC_2.1 getpid memmove msort_with_tmp strcpy strlen vfprintf write The first column is the number of samples for the symbol, the second column is the percentage of samples for this symbol relative to the overall samples for the executable, and the third column is the symbol name. To sort the output from the largest number of samples to the smallest (reverse order), use -r in conjunction with the -l option. -i symbol-name List sample data specific to a symbol name. For example, running: ~]# o prepo rt -l -i __g co nv_transfo rm_utf8_i nternal /l i b/tl s/l i bc-version. so returns the following output: samples % symbol name 12 100.000 __gconv_transform_utf8_internal The first line is a summary for the symbol/executable combination. The first column is the number of samples for the memory symbol. The second column is the percentage of samples for the memory address relative to the total number of samples for the symbol. The third column is the symbol name. -d This option lists sample data by symbols with more detail than the -l option. For example, with the following command: ~]# o prepo rt -d -i __g co nv_transfo rm_utf8_i nternal /l i b/tl s/l i bc-version. so this output is returned: vma samples % symbol name 00a98640 12 100.000 __gconv_transform_utf8_internal 00a98640 1 8.3333 00a9868c 2 16.6667 00a9869a 1 8.3333 00a986c1 1 8.3333 00a98720 1 8.3333 4 51 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 00a98749 00a98753 00a98789 00a98864 00a98869 00a98b08 1 1 1 1 1 1 8.3333 8.3333 8.3333 8.3333 8.3333 8.3333 The data is the same as the -l option except that for each symbol, each virtual memory address used is shown. For each virtual memory address, the number of samples and percentage of samples relative to the number of samples for the symbol is displayed. -e symbol-name… With this option, you can exclude some symbols from the output. Replace symbol-name with the comma-separated list of symbols you want to exclude. sessi o n:name Here, you can specify the full path to the session, a directory relative to the /var/l i b/o pro fi l e/sampl es/ directory, or if you are using o perf, a directory relative to . /o pro fi l e_d ata/sampl es/. 23.6.3. Get t ing More Det ailed Out put on t he Modules OProfile collects data on a system-wide basis for kernel- and user-space code running on the machine. However, once a module is loaded into the kernel, the information about the origin of the kernel module is lost. The module could come from the i ni trd file on boot up, the directory with the various kernel modules, or a locally created kernel module. As a result, when OProfile records samples for a module, it just lists the samples for the modules for an executable in the root directory, but this is unlikely to be the place with the actual code for the module. You will need to take some steps to make sure that analysis tools get the proper executable. To get a more detailed view of the actions of the module, you will need to either have the module " unstripped" (that is installed from a custom build) or have the debuginfo package installed for the kernel. Find out which kernel is running with the uname -a command, obtain the appropriate debuginfo package and install it on the machine. Then proceed with clearing out the samples from previous runs with the following command: o pco ntro l --reset To start the monitoring process, for example, on a machine with Westmere processor, run the following command: ~]# o pco ntro l --setup --vml i nux= /usr/l i b/d ebug /l i b/mo d ul es/`uname r`/vml i nux --event= C P U_C LK_UNHALT ED : 50 0 0 0 0 Then the detailed information, for instance, for the ext4 module can be obtained with: ~]# o prepo rt /ext4 -l --i mag e-path /l i b/mo d ul es/`uname -r`/kernel CPU: Intel Westmere microarchitecture, speed 2.667e+06 MHz (estimated) Counted CPU_CLK_UNHALTED events (Clock cycles when not halted) with a unit mask of 0x00 (No unit mask) count 500000 warning: could not check that the binary file /lib/modules/2.6.32- 4 52 Chapt er 2 3. O Profile 191.el6.x86_64/kernel/fs/ext4/ext4.ko has not been modified since the profile was taken. Results may be inaccurate. samples % symbol name 1622 9.8381 ext4_iget 1591 9.6500 ext4_find_entry 1231 7.4665 __ext4_get_inode_loc 783 4.7492 ext4_ext_get_blocks 752 4.5612 ext4_check_dir_entry 644 3.9061 ext4_mark_iloc_dirty 583 3.5361 ext4_get_blocks 583 3.5361 ext4_xattr_get 479 2.9053 ext4_htree_store_dirent 469 2.8447 ext4_get_group_desc 414 2.5111 ext4_dx_find_entry 23.6.4 . Using o panno tate The o panno tate tool tries to match the samples for particular instructions to the corresponding lines in the source code. The resulting generated files should have the samples for the lines at the left. It also puts in a comment at the beginning of each function listing the total samples for the function. For this utility to work, the appropriate debuginfo package for the executable must be installed on the system. On Red Hat Enterprise Linux, the debuginfo packages are not automatically installed with the corresponding packages that contain the executable. You have to obtain and install them separately. The general syntax for o panno tate is as follows: o panno tate --search-d i rs src-dir --so urce executable These command-line options are mandatory. Replace src-dir with a path to the directory containing the source code and specify the executable to be analyzed. See the o panno tate(1) manual page for a list of additional command line options. 23.7. Underst anding t he /dev/oprofile/ direct ory When using OProfile in legacy mode, the /d ev/o pro fi l e/ directory is used to store the file system for OProfile. On the other hand, o perf does not require /d ev/o pro fi l e/. Use the cat command to display the values of the virtual files in this file system. For example, the following command displays the type of processor OProfile detected: cat /d ev/o pro fi l e/cpu_type A directory exists in /d ev/o pro fi l e/ for each counter. For example, if there are 2 counters, the directories /d ev/o pro fi l e/0 / and /d ev/o pro fi l e/1/ exist. Each directory for a counter contains the following files: co unt — The interval between samples. enabl ed — If 0, the counter is off and no samples are collected for it; if 1, the counter is on and samples are being collected for it. event — The event to monitor. 4 53 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide extra — Used on machines with Nehalem processors to further specify the event to monitor. kernel — If 0, samples are not collected for this counter event when the processor is in kernelspace; if 1, samples are collected even if the processor is in kernel-space. uni t_mask — D efines which unit masks are enabled for the counter. user — If 0, samples are not collected for the counter event when the processor is in user-space; if 1, samples are collected even if the processor is in user-space. The values of these files can be retrieved with the cat command. For example: cat /d ev/o pro fi l e/0 /co unt 23.8. Example Usage While OProfile can be used by developers to analyze application performance, it can also be used by system administrators to perform system analysis. For example: Determine which applications and services are used the most on a system — o prepo rt can be used to determine how much processor time an application or service uses. If the system is used for multiple services but is underperforming, the services consuming the most processor time can be moved to dedicated systems. Determine processor usage — The C P U_C LK_UNHALT ED event can be monitored to determine the processor load over a given period of time. This data can then be used to determine if additional processors or a faster processor might improve system performance. 23.9. OProfile Support for Java OProfile allows you to profile dynamically compiled code (also known as " just-in-time" or JIT code) of the Java Virtual Machine (JVM). OProfile in Red Hat Enterprise Linux 7 includes built-in support for the JVM Tools Interface (JVMTI) agent library, which supports Java 1.5 and higher. 23.9.1. Profiling Java Code To profile JIT code from the Java Virtual Machine with the JVMTI agent, add the following to the JVM startup parameters: -ag entl i b: jvmti_oprofile Where jvmti_oprofile is a path to the OProfile agent. For 64-bit JVM, the path looks as follows: -ag entl i b: /usr/l i b6 4 /o pro fi l e/l i bjvmti _o pro fi l e. so Currently, you can add one command-line option: --d ebug , which enables debugging mode. Note The oprofile-jit package must be installed on the system in order to profile JIT code with OProfile. With this package, you gain the capability to show method-level information. 4 54 Chapt er 2 3. O Profile D epending on the JVM that you are using, you may have to install the debuginfo package for the JVM. For OpenJD K, this package is required, there is no debuginfo package for Oracle JD K. To keep the debug information packages synchronized with their respective non-debug packages, you also need to install the yum-plugin-auto-update-debug-info plug-in. This plug-in searches the debug information repository for corresponding updates. After successful setup, you can apply the standard profiling and analyzing tools described in previous sections To learn more about Java support in OProfile, see the OProfile Manual, which is linked from Section 23.12, “ Additional Resources” . 23.10. Graphical Int erface Some OProfile preferences can be set with a graphical interface. Make sure you have the o pro fi l e-g ui package that provides the OProfile GUI installed on your system. To start the interface, execute the o pro f_start command as root at a shell prompt. After changing any of the options, save them by clicking the Save and q ui t button. The preferences are written to /ro o t/. o pro fi l e/d aemo nrc, and the application exits. Note Exiting the application does not stop OProfile from sampling. On the Setup tab, to set events for the processor counters as discussed in Section 23.3.2, “ Setting Events to Monitor” , select the counter from the pulldown menu and select the event from the list. A brief description of the event appears in the text box below the list. Only events available for the specific counter and the specific architecture are displayed. The interface also displays whether the profiler is running and some brief statistics about it. 4 55 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 23.1. O Pro f ile Set u p On the right side of the tab, select the P ro fi l e kernel option to count events in kernel mode for the currently selected event, as discussed in Section 23.3.3, “ Separating Kernel and User-space Profiles” . If this option is not selected, no samples are collected for the kernel. Select the P ro fi l e user bi nari es option to count events in user mode for the currently selected event, as discussed in Section 23.3.3, “ Separating Kernel and User-space Profiles” . If this option is not selected, no samples are collected for user applications. 4 56 Chapt er 2 3. O Profile Use the C o unt text field to set the sampling rate for the currently selected event as discussed in Section 23.3.2.1, “ Sampling Rate” . If any unit masks are available for the currently selected event, as discussed in Section 23.3.2.2, “ Unit Masks” , they are displayed in the Uni t Masks area on the right side of the Setup tab. Select the check box beside the unit mask to enable it for the event. On the C o nfi g urati o n tab, to profile the kernel, enter the name and location of the vml i nux file for the kernel to monitor in the Kernel i mag e fi l e text field. To configure OProfile not to monitor the kernel, select No kernel i mag e. 4 57 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Fig u re 23.2. O Pro f ile C o n f ig u rat io n If the Verbo se option is selected, the o pro fi l ed daemon log includes more detailed information. If P er-appl i cati o n pro fi l es is selected, OProfile generates per-application profiles for libraries. This is equivalent to the o pco ntro l --separate= l i brary command. If P erappl i cati o n pro fi l es, i ncl ud i ng kernel is selected, OProfile generates per-application profiles for the kernel and kernel modules as discussed in Section 23.3.3, “ Separating Kernel and User-space Profiles” . This is equivalent to the o pco ntro l --separate= kernel command. To force data to be written to samples files as discussed in Section 23.6, “ Analyzing the D ata” , click the Fl ush button. This is equivalent to the o pco ntro l --d ump command. To start OProfile from the graphical interface, click Start. To stop the profiler, click Sto p. Exiting the application does not stop OProfile from sampling. 23.11. OProfile and Syst emT ap SystemTap is a tracing and probing tool that allows users to study and monitor the activities of the operating system in fine detail. It provides information similar to the output of tools like netstat, ps, to p, and i o stat; however, SystemTap is designed to provide more filtering and analysis options for the collected information. While using OProfile is suggested in cases of collecting data on where and why the processor spends time in a particular area of code, it is less usable when finding out why the processor stays idle. You might want to use SystemTap when instrumenting specific places in code. Because SystemTap allows you to run the code instrumentation without having to stop and restart the instrumented code, it is particularly useful for instrumenting the kernel and daemons. For more information on SystemTap, see SystemTap Beginners Guide. 23.12. Addit ional Resources To learn more about OProfile and how to configure it, see the following resources. Inst alled Document at ion /usr/share/d o c/o pro fi l e-version/o pro fi l e. html — OProfile Manual o pro fi l e(1) manual page — D iscusses o pco ntro l , o prepo rt, o panno tate, and o phel p o perf(1) manual page Online Document at ion http://oprofile.sourceforge.net/ — upstream documentation that contains documentation, mailing lists, IRC channels, and more about the OProfile project. In Red Hat Enterprise Linux 7, OProfile version 0.9.9. is provided. See Also 4 58 Chapt er 2 3. O Profile SystemTap Beginners Guide — Provides basic instructions on how to use SystemTap to monitor different subsystems of Re Hat Enterprise Linux in finer detail. 4 59 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Part VII. Kernel, Module and Driver Configuration This part covers various tools that assist administrators with kernel customization. 4 60 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader Chapter 24. Working with the GRUB 2 Boot Loader Red Hat Enterprise Linux 7 is distributed with the GNU GRand Unified Boot loader (GRUB) version 2 boot loader, which allows the user to select an operating system or kernel to be loaded at system boot time. GRUB 2 also allows the user to pass arguments to the kernel. 24 .1. Configuring t he GRUB 2 Boot Loader GRUB 2 reads its configuration from the /bo o t/g rub2/g rub. cfg file on traditional BIOS-based machines and from the /bo o t/efi /EFI/red hat/g rub. cfg file on UEFI machines. This file contains menu information, however, it is not supposed to be edited as it is generated by the /u sr/sb in /g ru b 2- mkco n f ig utility based on Linux kernels located in the /bo o t/ directory, template files located in /etc/g rub. d /, and custom settings in the /etc/d efaul t/g rub file. Any manual edits could therefore cause the changes to be lost during updates. The GRUB 2 configuration file, g rub. cfg , is automatically updated each time a new kernel is installed. Note that any changes to /etc/d efaul t/g rub require rebuilding the g rub. cfg file. To update the GRUB 2 configuration file manually, use the g rub2-mkco nfi g -o command as follows: On BIOS-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/g rub2/g rub. cfg On UEFI-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/efi /EFI/red hat/g rub. cfg Among various code snippets and directives, the g rub. cfg configuration file contains one or more menuentry blocks, each representing a single GRUB 2 boot menu entry. These blocks always start with the menuentry keyword followed by a title, list of options, and an opening curly bracket, and end with a closing curly bracket. Anything between the opening and closing bracket should be indented. For example, the following is a sample menuentry block for Red Hat Enterprise Linux 7 with Linux kernel 3.8.0-0.40.el7.x86_64: menuentry 'Red Hat Enterprise Linux Server' --class red --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-c60731dc9046-4000-9182-64bdcce08616' { load_video set gfxpayload=keep insmod gzio insmod part_msdos insmod xfs set root='hd0,msdos1' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 --hint='hd0,msdos1' 19d9e294-65f8-4e37-8e73-d41d6daa6e58 else search --no-floppy --fs-uuid --set=root 19d9e294-65f8-4e378e73-d41d6daa6e58 fi echo 'Loading Linux 3.8.0-0.40.el7.x86_64 ...' linux16 /vmlinuz-3.8.0-0.40.el7.x86_64 root=/dev/mapper/rhelroot ro rd.md=0 rd.dm=0 rd.lvm.lv=rhel/swap crashkernel=auto rd.luks=0 4 61 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide vconsole.keymap=us rd.lvm.lv=rhel/root rhgb quiet echo 'Loading initial ramdisk ...' initrd /initramfs-3.8.0-0.40.el7.x86_64.img } Each menuentry block that represents an installed Linux kernel contains l i nux on 64-bit IBM POWER Series, l i nux16 on x86_64 BIOS-based systems, and l i nuxefi on UEFI-based systems. Then the i ni trd directives followed by the path to the kernel and the i ni tramfs image respectively. If a separate /bo o t partition was created, the paths to the kernel and the i ni tramfs image are relative to /bo o t. In the example above, the i ni trd /i ni tramfs-3. 8. 0 0 . 4 0 . el 7. x86 _6 4 . i mg line means that the i ni tramfs image is actually located at /bo o t/i ni tramfs-3. 8. 0 -0 . 4 0 . el 7. x86 _6 4 . i mg when the ro o t file system is mounted, and likewise for the kernel path. The kernel version number as given on the l i nux16 /vml i nuz-kernel _versi o n line must match the version number of the i ni tramfs image given on the i ni trd /i ni tramfskernel _versi o n. i mg line of each menuentry block. For more information on how to verify the initial RAM disk image, see Section 25.5, “ Verifying the Initial RAM D isk Image” . Note In menuentry blocks, the i ni trd directive must point to the location (relative to the /bo o t/ directory if it is on a separate partition) of the i ni tramfs file corresponding to the same kernel version. This directive is called i ni trd because the previous tool which created initial RAM disk images, mki ni trd , created what were known as i ni trd files. The g rub. cfg directive remains i ni trd to maintain compatibility with other tools. The file-naming convention of systems using the d racut utility to create the initial RAM disk image is i ni tramfs-kernel_version. i mg . For information on using D racu t , see Section 25.5, “ Verifying the Initial RAM D isk Image” . 24 .2. Cust omiz ing GRUB 2 Menu GRUB 2 scripts search the user's computer and build a boot menu based on what operating systems the scripts find. To reflect the latest system boot options, the boot menu is rebuilt automatically when the kernel is updated or a new kernel is added. However, users may want to build a menu containing specific entries or to have the entries in a specific order. GRUB 2 allows basic customization of the boot menu to give users control of what actually appears on the screen. GRUB 2 uses a series of scripts to build the menu; these are located in the /etc/g rub. d / directory. The following files are included: 0 0 _head er, which loads GRUB 2 settings from the /etc/d efaul t/g rub file. 0 1_users, which is created only when a boot loader password is assigned in a kickst art file. 10 _l i nux, which locates kernels in the default partition of Red Hat Enterprise Linux. 30 _o s-pro ber, which builds entries for operating systems found on other partitions. 4 0 _custo m, a template, which can be used to create additional menu entries. 4 62 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader Scripts from the /etc/g rub. d / directory are read in alphabetical order and can be therefore renamed to change the boot order of specific menu entries. Important With the G R UB_T IMEO UT key set to 0 in the /etc/d efaul t/g rub file, GRUB 2 does not display the list of bootable kernels when the system starts up. In order to display this list when booting, press and hold any alphanumeric key when the BIOS information is displayed; GRUB 2 will present you with the GRUB menu. 24 .2.1. Changing t he Default Boot Ent ry By default, the key for the G R UB_D EFAULT directive in the /etc/d efaul t/g rub file is the word saved . This instructs GRUB 2 to load the kernel specified by the saved _entry directive in the GRUB 2 environment file, located at /bo o t/g rub2/g rubenv. You can set another GRUB record to be the default, using the g rub2-set-d efaul t command, which will update the GRUB 2 environment file. By default, the saved _entry value is set to the name of latest installed kernel of package type kernel. This is defined in /etc/sysco nfi g /kernel by the UP D AT ED EFAULT and D EFAULT KER NEL directives. The file can be viewed by the ro o t user as follows: ~]# cat /etc/sysco nfi g /kernel # UPDATEDEFAULT specifies if new-kernel-pkg should make # new kernels the default UPDATEDEFAULT=yes # DEFAULTKERNEL specifies the default kernel package type DEFAULTKERNEL=kernel The D EFAULT KER NEL directive specifies what package type will be used as the default. Installing a package of type kernel-debug will not change the default kernel while the D EFAULT KER NEL is set to package type kernel. GRUB 2 supports using a numeric value as the key for the saved _entry directive to change the default order in which the operating systems are loaded. To specify which operating system should be loaded first, pass its number to the g rub2-set-d efaul t command. For example: ~]# g rub2-set-d efaul t 2 Note that the position of a menu entry in the list is denoted by a number starting with zero; therefore, in the example above, the third entry will be loaded. This value will be overwritten by the name of the next kernel to be installed. To force a system to always use a particular menu entry, use the menu entry name as the key to the G R UB_D EFAULT directive in the /etc/d efaul t/g rub file. To list the available menu entries, run the following command as ro o t: ~]# awk -F\' ' $1= = "menuentry " {pri nt $2}' /etc/g rub2. cfg Changes to /etc/d efaul t/g rub require rebuilding the g rub. cfg file as follows: On BIOS-based machines, issue the following command as ro o t: 4 63 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# g rub2-mkco nfi g -o /bo o t/g rub2/g rub. cfg On UEFI-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/efi /EFI/red hat/g rub. cfg 24 .2.2. Edit ing an Ent ry Ke rne l Param e t e rs To use a kernel parameter only during a single boot process, when the GRUB 2 boot menu appears, move the cursor to the kernel you want to start, and press the e key to edit the kernel parameters. For example, to run the system in emergency mode, add the emergency parameter at the end of the l i nux16 line: linux16 /vmlinuz-3.10.0-0.rc4.59.el7.x86_64 root=/dev/mapper/rhelroot ro rd.md=0 rd.dm=0 rd.lvm.lv=rhel/swap crashkernel=auto rd.luks=0 vconsole.keymap=us rd.lvm.lv=rhel/root rhgb quiet emergency These settings are not persistent and apply only for a single boot. To make the settings persistent, edit values of the G R UB_C MD LINE_LINUX key in the /etc/d efaul t/g rub file. For example, if you want to enable emergency mode for each boot, use: GRUB_CMDLINE_LINUX="emergency" Note that you can specify multiple parameters for the G R UB_C MD LINE_LINUX key, similarly to adding the parameters in the GRUB 2 boot menu. For example: GRUB_CMDLINE_LINUX="console=tty0 console=ttyS0,9600n8" Where co nso l e= tty0 is the first virtual terminal and co nso l e= ttyS0 is the serial terminal to be used. Changes to /etc/d efaul t/g rub require rebuilding the g rub. cfg file as follows: On BIOS-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/g rub2/g rub. cfg On UEFI-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/efi /EFI/red hat/g rub. cfg 24 .2.3. Adding a new Ent ry When executing the g rub2-mkco nfi g command, GRUB 2 searches for Linux kernels and other operating systems based on the files located in the /etc/g rub. d / directory. The /etc/g rub. d /10 _l i nux script searches for installed Linux kernels on the same partition. The /etc/g rub. d /30 _o s-pro ber script searches for other operating systems. Menu entries are also automatically added to the boot menu when updating the kernel. 4 64 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader The 4 0 _custo m file located in the /etc/g rub. d / directory is a template for custom entries and looks as follows: # !/bin/sh e xec tail -n +3 $0 # This file provides an easy way to add custom menu entries. Simply type the # menu entries you want to add after this comment. Be careful not to change # the 'exec tail' line above. This file can be edited or copied. Note that as a minimum, a valid menu entry must include at least the following: menuentry " "{ } 24 .2.4 . Creat ing a Cust om Menu If you do not want menu entries to be updated automatically, you can create a custom menu. Important Before proceeding, back up the contents of the /etc/g rub. d / directory in case you need to revert the changes later. Note Note that modifying the /etc/d efaul t/g rub file does not have any effect on creating custom menus. 1. On BIOS-based machines, copy the contents of /bo o t/g rub2/g rub. cfg , or, on UEFI machines, copy the contents of /bo o t/efi /EFI/red hat/g rub. cfg . Put the content of the g rub. cfg into the /etc/g rub. d /4 0 _custo m file below the existing header lines. The executable part of the 4 0 _custo m script has to be preserved. 2. From the content put into the /etc/g rub. d /4 0 _custo m file, only the menuentry blocks are needed to create the custom menu. The /bo o t/g rub2/g rub. cfg and /bo o t/efi /EFI/red hat/g rub. cfg files might contain function specifications and other content above and below the menuentry blocks. If you put these unnecessary lines into the 4 0 _custo m file in the previous step, erase them. This is an example of a custom 4 0 _custo m script: # !/bin/sh e xec tail -n +3 $0 # This file provides an easy way to add custom menu entries. Simply type the # menu entries you want to add after this comment. Be careful not 4 65 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide to change the 'exec tail' line above. # m enuentry 'First custom entry' --class red --class gnu-linux -class gnu --class os $menuentry_id_option 'gnulinux-3.10.067.el7.x86_64-advanced-32782dd0-4b47-4d56-a740-2076ab5e5976' { load_video set gfxpayload=keep insmod gzio insmod part_msdos insmod xfs set root='hd0,msdos1' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root -hint='hd0,msdos1' 7885bba1-8aa7-4e5d-a7ad-821f4f52170a else search --no-floppy --fs-uuid --set=root 7885bba1-8aa74e5d-a7ad-821f4f52170a fi linux16 /vmlinuz-3.10.0-67.el7.x86_64 root=/dev/mapper/rhel-root ro rd.lvm.lv=rhel/root vconsole.font=latarcyrheb-sun16 rd.lvm.lv=rhel/swap vconsole.keymap=us crashkernel=auto rhgb quiet LANG=en_US.UTF-8 initrd16 /initramfs-3.10.0-67.el7.x86_64.img } m enuentry 'Second custom entry' --class red --class gnu-linux -class gnu --class os $menuentry_id_option 'gnulinux-0-rescue07f43f20a54c4ce8ada8b70d33fd001c-advanced-32782dd0-4b47-4d56-a7402076ab5e5976' { load_video insmod gzio insmod part_msdos insmod xfs set root='hd0,msdos1' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root -hint='hd0,msdos1' 7885bba1-8aa7-4e5d-a7ad-821f4f52170a else search --no-floppy --fs-uuid --set=root 7885bba1-8aa74e5d-a7ad-821f4f52170a fi linux16 /vmlinuz-0-rescue-07f43f20a54c4ce8ada8b70d33fd001c root=/dev/mapper/rhel-root ro rd.lvm.lv=rhel/root vconsole.font=latarcyrheb-sun16 rd.lvm.lv=rhel/swap vconsole.keymap=us crashkernel=auto rhgb quiet initrd16 /initramfs-0-rescue07f43f20a54c4ce8ada8b70d33fd001c.img } 3. Remove all files from the /etc/g rub. d directory except the following: 0 0 _head er, 4 0 _custo m, 0 1_users (if it exists), 4 66 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader and R EAD ME. Alternatively, if you want to keep the files in the /etc/g rub2. d / directory, make them unexecutable by running the chmo d a-x command. 4. Edit, add, or remove menu entries in the 4 0 _custo m file as desired. 5. Update the g rub. cfg file by running the g rub2-mkco nfi g -o command as follows: On BIOS-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/g rub2/g rub. cfg On UEFI-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/efi /EFI/red hat/g rub. cfg 24 .3. GRUB 2 Password Prot ect ion GRUB 2 supports both plain-text and encrypted passwords in the GRUB 2 template files. To enable the use of passwords, specify a superuser who can reach the protected entries. Other users can be specified to access these entries as well. Menu entries can be password-protected for booting by adding one or more users to the menu entry as described in Section 24.3.1, “ Setting Up Users and Password Protection, Specifying Menu Entries” . To use encrypted passwords, see Section 24.3.2, “ Password Encryption” . Warning If you do not use the correct format for the menu, or modify the configuration in an incorrect way, you might be unable to boot your system. All menu entries can be password-protected against changes by setting superusers, which can be done in the /etc/g rub. d /0 0 _head er or the /etc/g rub. d /0 1_users file. The 0 0 _head er file is very complicated and, if possible, avoid making modifications in this file. Menu entries should be placed in the /etc/g rub. d /4 0 _custo m and users in the /etc/g rub. d /0 1_users file. The 0 1_users file is generated by the installation application an aco n d a when a grub boot loader password is used in a kickst art template (but it should be created and used it if it does not exist). Examples in this section adopt this policy. 24 .3.1. Set t ing Up Users and Password Prot ect ion, Specifying Menu Ent ries 1. To specify a superuser, add the following lines in the /etc/g rub. d /0 1_users file, where jo hn is the name of the user designated as the superuser, and jo hnspasswo rd is the superuser's password: cat < command to reinstall GRUB 2 if the system is operating normally. For example: ~]# g rub2-i nstal l /d ev/sd a 24 .4 .2. Reset t ing and Reinst alling GRUB 2 This method completely removes all GRUB 2 configuration files and system settings. Apply this method to reset all configuration settings to their default values. Removing of the configuration files and subsequent reinstalling of GRUB 2 fixes failures caused by corrupted files and incorrect configuration. To do so, as ro o t, follow these steps: 1. Run the rm /etc/g rub. d /* command; 2. Run the rm /etc/sysco nfi g /g rub command; 3. For EFI systems o n ly, run the following command: ~]# yum rei nstal l g rub2-efi shi m 4. Update the g rub. cfg file by running the g rub2-mkco nfi g -o command as follows: On BIOS-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/g rub2/g rub. cfg On UEFI-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/efi /EFI/red hat/g rub. cfg 5. Now follow the procedure in Section 24.4.1, “ Using the grub2-install Command” to restore GRUB2 on the /bo o t/ partition. 24 .5. GRUB 2 over Serial Console If you use computers with no display or keyboard, it can be very useful to control the machines through serial communications. 24 .5.1. Configuring GRUB 2 In order to use GRUB 2 over a serial line, add the following two lines in the /etc/d efaul t/g rub file: GRUB_TERMINAL="serial" GRUB_SERIAL_COMMAND="serial --speed=9600 --unit=0 --word=8 --parity=no -stop=1" The first line disables the graphical terminal. Note that specifying the G R UB_T ER MINAL key overrides values of G R UB_T ER MINAL_INP UT and G R UB_T ER MINAL_O UT P UT . On the second line, adjust the baud rate, parity, and other values to fit your environment and hardware. A much higher baud rate, for example 11520 0 , is preferable for tasks such as following log files. Once you have completed the changes in the /etc/d efaul t/g rub file, it is necessary to update the GRUB 2 configuration file. 4 70 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader Update the g rub. cfg file by running the g rub2-mkco nfi g -o command as follows: On BIOS-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/g rub2/g rub. cfg On UEFI-based machines, issue the following command as ro o t: ~]# g rub2-mkco nfi g -o /bo o t/efi /EFI/red hat/g rub. cfg Note In order to access the grub terminal over a serial connection an additional option must be added to a kernel definition to make that particular kernel monitor a serial connection. For example: console=ttyS0,9600n8 Where co nso l e= ttyS0 is the serial terminal to be used, 9 6 0 0 is the baud rate, n is for no parity, and 8 is the word length in bits. A much higher baud rate, for example 11520 0 , is preferable for tasks such as following log files. For more information on adding kernel options, see Section 24.2.2, “ Editing an Entry” . For more information on serial console settings, see Section 26.8, “ Installable and External D ocumentation” 24 .5.2. Using screen t o Connect t o t he Serial Console The screen tool serves as a capable serial terminal. To install it, run as ro o t: ~]# yum i nstal l screen To connect to your machine using the serial console, run the following command: ~]$ screen /d ev/ By default, if no option is specified, screen uses the standard 9600 baud rate. To set a different baud rate, run: ~]$ screen /d ev/ 11520 0 To end the session in screen , press C trl +a, type : q ui t and press Enter. See the screen(1) manual page for additional options and detailed information. 24 .6. T erminal Menu Edit ing During Boot Menu entries can be modified and arguments passed to the kernel on boot. This is done using the menu entry editor interface, which is triggered when pressing the e key on a selected menu entry in the boot loader menu. The Esc key discards any changes and reloads the standard menu interface. 4 71 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide The c key loads the command line interface. The command line interface is the most basic GRUB interface, but it is also the one that grants the most control. The command line makes it possible to type any relevant GRUB commands followed by the Enter key to execute them. This interface features some advanced features similar to sh ell, including T ab key completion based on context, and C trl +a to move to the beginning of a line and C trl +e to move to the end of a line. In addition, the arro w, Ho me, End , and D el ete keys work as they do in the bash shell. 24 .6.1. Boot ing t o Rescue Mode Rescue mode provides a convenient single-user environment and allows you to repair your system in situations when it is unable to complete a normal booting process. In rescue mode, the system attempts to mount all local file systems and start some important system services, but it does not activate network interfaces or allow more users to be logged into the system at the same time. In Red Hat Enterprise Linux 7, rescue mode is equivalent to single user mode and requires the ro o t password. 1. To enter rescue mode during boot, on the GRUB 2 boot screen, press the e key for edit. 2. Add the following parameter at the end of the l i nux line on 64-Bit IBM Power Series, the l i nux16 line on x86-64 BIOS-based systems, or the l i nuxefi line on UEFI systems: systemd.unit=rescue.target Press C trl +a and C trl +e to jump to the start and end of the line, respectively. On some systems, Ho me and End might also work. Note that equivalent parameters, 1, s, and single, can be passed to the kernel as well. 3. Press C trl +x to boot the system with the parameter. 24 .6.2. Boot ing t o Emergency Mode Emergency mode provides the most minimal environment possible and allows you to repair your system even in situations when the system is unable to enter rescue mode. In emergency mode, the system mounts the ro o t file system only for reading, does not attempt to mount any other local file systems, does not activate network interfaces, and only starts few essential services. In Red Hat Enterprise Linux 7, emergency mode requires the ro o t password. 1. To enter emergency mode, on the GRUB 2 boot screen, press the e key for edit. 2. Add the following parameter at the end of the l i nux line on 64-Bit IBM Power Series, the l i nux16 line on x86-64 BIOS-based systems, or the l i nuxefi line on UEFI systems: systemd.unit=emergency.target Press C trl +a and C trl +e to jump to the start and end of the line, respectively. On some systems, Ho me and End might also work. Note that equivalent parameters, emergency and -b, can be passed to the kernel as well. 3. Press C trl +x to boot the system with the parameter. 24 .6.3. Changing and Reset t ing t he Root Password 4 72 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader Setting up the ro o t password is a mandatory part of the Red Hat Enterprise Linux 7 installation. If you forget or lose the ro o t password it is possible to reset it, however users who are members of the wheel group can change the ro o t password as follows: ~]$ sud o passwd ro o t Note that in GRUB 2, resetting the password is no longer performed in single-user mode as it was in GRUB included in Red Hat Enterprise Linux 6. The ro o t password is now required to operate in si ng l e-user mode as well as in emerg ency mode. Two procedures for resetting the ro o t password are shown here: Procedure 24.1, “ Resetting the Root Password Using an Installation D isk” takes you to a shell prompt, without having to edit the grub menu. It is the shorter of the two procedures and it is also the recommended method. You can use a boot disk or a normal Red Hat Enterprise Linux 7 installation disk. Procedure 24.2, “ Resetting the Root Password Using rd.break” makes use of rd . break to interrupt the boot process before control is passed from i ni tramfs to systemd . The disadvantage of this method is that it requires more steps, includes having to edit the GRUB menu, and involves choosing between a possibly time consuming SELinux file relabel or changing the SELinux enforcing mode and then restoring the SELinux security context for /etc/shad o w/ when the boot completes. Pro ced u re 24 .1. R eset t in g t h e R o o t Passwo rd U sin g an In st allat io n D isk 1. Start the system and when BIOS information is displayed, select the option for a boot menu and select to boot from the installation disk. 2. Choose T ro u b lesh o o t in g . 3. Choose R escu e a R ed H at En t erp rise Lin u x Syst em. 4. Choose C o n t in u e which is the default option. At this point you will be promoted for a passphrase if an encrypted file system is found. 5. Press O K to acknowledge the information displayed until the shell prompt appears. 6. Change the file system ro o t as follows: sh-4.2# chro o t /mnt/sysi mag e 7. Enter the passwd command and follow the instructions displayed on the command line to change the ro o t password. 8. Remove the auto rel abl e file to prevent a time consuming SELinux relabel of the disk: sh-4.2# rm -f /. auto rel abel 9. Enter the exi t command to exit the chro o t environment. 10. Enter the exi t command again to resume the initialization and finish the system boot. Pro ced u re 24 .2. R eset t in g t h e R o o t Passwo rd U sin g rd .b reak 1. Start the system and, on the GRUB 2 boot screen, press the e key for edit. 4 73 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide 2. Remove the rhg b and q ui et parameters from the end, or near the end, of the l i nux16 line, or l i nuxefi on UEFI systems. Press C trl +a and C trl +e to jump to the start and end of the line, respectively. On some systems, Ho me and End might also work. Important The rhg b and q ui et parameters must be removed in order to enable system messages. 3. Add the following parameters at the end of the l i nux line on 64-Bit IBM Power Series, the l i nux16 line on x86-64 BIOS-based systems, or the l i nuxefi line on UEFI systems: rd.break enforcing=0 Adding the enfo rci ng = 0 option enables omitting the time consuming SELinux relabeling process. The i ni tramfs will stop before passing control to the Linux kernel, enabling you to work with the ro o t file system. Note that the i ni tramfs prompt will appear on the last console specified on the Linux line. 4. Press C trl +x to boot the system with the changed parameters. With an encrypted file system, a password is required at this point. However the password prompt might not appear as it is obscured by logging messages. You can press the Backspace key to see the prompt. Release the key and enter the password for the encrypted file system, while ignoring the logging messages. The i ni tramfs swi tch_ro o t prompt appears. 5. The file system is mounted read-only on /sysro o t/. You will not be allowed to change the password if the file system is not writable. Remount the file system as writable: switch_root:/# mo unt -o remo unt,rw /sysro o t 6. The file system is remounted with write enabled. Change the file system's ro o t as follows: switch_root:/# chro o t /sysro o t The prompt changes to sh-4 . 2#. 7. Enter the passwd command and follow the instructions displayed on the command line to change the ro o t password. Note that if the system is not writable, the p asswd tool fails with the following error: Authentication token manipulation error 4 74 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader 8. Updating the password file results in a file with the incorrect SELinux security context. To relabel all files on next system boot, enter the following command: sh-4.2# to uch /. auto rel abel Alternatively, to save the time it takes to relabel a large disk, you can omit this step provided you included the enfo rci ng = 0 option in step 3. 9. Remount the file system as read only: sh-4.2# mo unt -o remo unt,ro / 10. Enter the exi t command to exit the chro o t environment. 11. Enter the exi t command again to resume the initialization and finish the system boot. With an encrypted file system, a pass word or phrase is required at this point. However the password prompt might not appear as it is obscured by logging messages. You can press and hold the Backspace key to see the prompt. Release the key and enter the password for the encrypted file system, while ignoring the logging messages. Note Note that the SELinux relabeling process can take a long time. A system reboot will occur automatically when the process is complete. 12. If you added the enfo rci ng = 0 option in step 3 and omitted the to uch /. auto rel abel command in step 8, enter the following command to restore the /etc/shad o w file's SELinux security context: ~]# resto rco n /etc/shad o w Enter the following commands to turn SELinux policy enforcement back on and verify that it is on: ~]# setenfo rce 1 ~]# g etenfo rce Enforcing 24 .7. Unified Ext ensible Firmware Int erface (UEFI) Secure Boot The Unified Extensible Firmware Interface (UEFI) Secure Boot technology ensures that the system firmware checks whether the system boot loader is signed with a cryptographic key authorized by a database of public keys contained in the firmware. With signature verification in the next-stage boot loader and kernel, it is possible to prevent the execution of kernel space code which has not been signed by a trusted key. A chain of trust is established from the firmware to the signed drivers and kernel modules as follows. The first-stage boot loader, shi m. efi , is signed by a UEFI private key and authenticated by a public key, signed by a certificate authority (CA), stored in the firmware database. The shi m. efi contains the Red Hat public key, “ Red Hat Secure Boot (CA key 1)” , which is used to authenticate 4 75 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide both the GRUB 2 boot loader, g rubx6 4 . efi , and the Red Hat kernel. The kernel in turn contains public keys to authenticate drivers and modules. Secure Boot is the boot path validation component of the Unified Extensible Firmware Interface (UEFI) specification. The specification defines: a programming interface for cryptographically protected UEFI variables in non-volatile storage, how the trusted X.509 root certificates are stored in UEFI variables, validation of UEFI applications like boot loaders and drivers, procedures to revoke known-bad certificates and application hashes. UEFI Secure Boot does not prevent the installation or removal of second-stage boot loaders, nor require explicit user confirmation of such changes. Signatures are verified during booting, not when the boot loader is installed or updated. Therefore, UEFI Secure Boot does not stop boot path manipulations, it helps in the detection of unauthorized changes. A new boot loader or kernel will work as long as it is signed by a key trusted by the system. 24 .7.1. UEFI Secure Boot Support in Red Hat Ent erprise Linux 7 Red Hat Enterprise Linux 7 includes support for the UEFI Secure Boot feature, which means that Red Hat Enterprise Linux 7 can be installed and run on systems where UEFI Secure Boot is enabled. On UEFI-based systems with the Secure Boot technology enabled, all drivers that are loaded must be signed with a trusted key, otherwise the system will not accept them. All drivers provided by Red Hat are signed by one of Red Hat's private keys and authenticated by the corresponding Red Hat public key in the kernel. If you want to load externally built drivers, drivers that are not provided on the Red Hat Enterprise Linux D VD , you must make sure these drivers are signed as well. Information on signing custom drivers is available in Section 26.7, “ Signing Kernel Modules for Secure Boot” . Re st rict io ns Im po se d by UEFI Se cure Bo o t As UEFI Secure Boot support in Red Hat Enterprise Linux 7 is designed to ensure that the system only runs kernel mode code after its signature has been properly authenticated, certain restrictions exist. GRUB 2 module loading is disabled as there is no infrastructure for signing and verification of GRUB 2 modules, which means allowing them to be loaded would constitute execution of untrusted code inside the security perimeter that Secure Boot defines. Instead, Red Hat provides a signed GRUB 2 binary that has all the modules supported on Red Hat Enterprise Linux 7 already included. More detailed information is available in the Red Hat Knowledgebase article Restrictions Imposed by UEFI Secure Boot. 24 .8. Addit ional Resources Please see the following resources for more information on the GRUB 2 boot loader: Inst alled Document at ion 4 76 Chapt er 2 4 . Working wit h t he G RUB 2 Boot Loader /usr/share/d o c/g rub2-to o l s- — This directory contains information about using and configuring GRUB 2. corresponds to the version of the GRUB 2 package installed. i nfo g rub2 — The GRUB 2 info page contains a tutorial, a user reference manual, a programmer reference manual, and a FAQ document about GRUB 2 and its usage. Inst allable and Ext ernal Document at ion /usr/share/d o c/kernel -d o c-kernel_version/D o cumentati o n/seri al co nso l e. txt — This file, which is provided by the kernel-doc package, contains information on the serial console. Before accessing the kernel documentation, you must run the following command as ro o t: ~]# yum i nstal l kernel -d o c Red Hat Installation Guide — The Installation Guide provides basic information on GRUB 2, for example, installation, terminology, interfaces, and commands. 4 77 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Chapter 25. Manually Upgrading the Kernel The Red Hat Enterprise Linux kernel is custom-built by the Red Hat Enterprise Linux kernel team to ensure its integrity and compatibility with supported hardware. Before Red Hat releases a kernel, it must first pass a rigorous set of quality assurance tests. Red Hat Enterprise Linux kernels are packaged in the RPM format so that they are easy to upgrade and verify using the Yu m or Packag eK it package managers. Packag eK it automatically queries the Red Hat Network servers and informs you of packages with available updates, including kernel packages. This chapter is therefore only useful for users who need to manually update a kernel package using the rpm command instead of yum. Warning Whenever possible, use either the Yu m or Packag eK it package manager to install a new kernel because they always install a new kernel instead of replacing the current one, which could potentially leave your system unable to boot. Warning Building a custom kernel is not supported by the Red Hat Global Services Support team, and therefore is not explored in this manual. For more information on installing kernel packages with Yu m, see Section 7.1.2, “ Updating Packages” . For information on Red Hat Network, see related documents located on Customer Portal. 25.1. Overview of Kernel Packages Red Hat Enterprise Linux contains the following kernel packages: kernel — Contains the kernel for single, multicore and multiprocessor systems. kernel-debug — Contains a kernel with numerous debugging options enabled for kernel diagnosis, at the expense of reduced performance. kernel-devel — Contains the kernel headers and makefiles sufficient to build modules against the kernel package. kernel-debug-devel — Contains the development version of the kernel with numerous debugging options enabled for kernel diagnosis, at the expense of reduced performance. kernel-doc — D ocumentation files from the kernel source. Various portions of the Linux kernel and the device drivers shipped with it are documented in these files. Installation of this package provides a reference to the options that can be passed to Linux kernel modules at load time. By default, these files are placed in the /usr/share/d o c/kernel -d o c-kernel_version/ directory. 4 78 Chapt er 2 5. Manually Upgrading t he Kernel kernel-headers — Includes the C header files that specify the interface between the Linux kernel and user-space libraries and programs. The header files define structures and constants that are needed for building most standard programs. linux-firmware — Contains all of the firmware files that are required by various devices to operate. perf — This package contains the p erf tool, which enables performance monitoring of the Linux kernel. kernel-abi-whitelists — Contains information pertaining to the Red Hat Enterprise Linux kernel ABI, including a lists of kernel symbols that are needed by external Linux kernel modules and a yum plug-in to aid enforcement. kernel-tools — Contains tools for manipulating the Linux kernel and supporting documentation. 25.2. Preparing t o Upgrade Before upgrading the kernel, it is recommended that you take some precautionary steps. First, ensure that working boot media exists for the system in case a problem occurs. If the boot loader is not configured properly to boot the new kernel, you can use this media to boot into Red Hat Enterprise Linux. USB media often comes in the form of flash devices sometimes called pen drives, thumb disks, or keys, or as an externally-connected hard disk device. Almost all media of this type is formatted as a VFAT file system. You can create bootable USB media on media formatted as ext2, ext3, ext4 , or VFAT . You can transfer a distribution image file or a minimal boot media image file to USB media. Make sure that sufficient free space is available on the device. Around 4 G B is required for a distribution D VD image, around 70 0 MB for a distribution CD image, or around 10 MB for a minimal boot media image. You must have a copy of the bo o t. i so file from a Red Hat Enterprise Linux installation D VD , or installation CD -ROM #1, and you need a USB storage device formatted with the VFAT file system and around 16 MB of free space. The following procedure will not affect existing files on the USB storage device unless they have the same path names as the files that you copy onto it. To create USB boot media, perform the following commands as the ro o t user: 1. Install the syslinux package if it is not installed on your system. To do so, as root, run the yum i nstal l syslinux command. 2. Install the SYSLIN U X bootloader on the USB storage device: ~]# sysl i nux /d ev/sdX1 ...where sdX is the device name. 3. Create mount points for bo o t. i so and the USB storage device: ~]# mkd i r /mnt/i so bo o t /mnt/d i skbo o t 4. Mount bo o t. i so : ~]# mo unt -o l o o p bo o t. i so /mnt/i so bo o t 5. Mount the USB storage device: 4 79 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# mo unt /d ev/sdX1 /mnt/d i skbo o t 6. Copy the ISO LIN U X files from the bo o t. i so to the USB storage device: ~]# cp /mnt/i so bo o t/i so l i nux/* /mnt/d i skbo o t 7. Use the i so l i nux. cfg file from bo o t. i so as the sysl i nux. cfg file for the USB device: ~]# g rep -v l o cal /mnt/i so bo o t/i so l i nux/i so l i nux. cfg > /mnt/d i skbo o t/sysl i nux. cfg 8. Unmount bo o t. i so and the USB storage device: ~]# umo unt /mnt/i so bo o t /mnt/d i skbo o t 9. You should reboot the machine with the boot media and verify that you are able to boot with it before continuing. Alternatively, on systems with a floppy drive, you can create a boot diskette by installing the mkbootdisk package and running the mkbo o td i sk command as ro o t. See man mkbo o td i sk man page after installing the package for usage information. To determine which kernel packages are installed, execute the command yum l i st i nstal l ed "kernel -*" at a shell prompt. The output will comprise some or all of the following packages, depending on the system's architecture, and the version numbers might differ: ~]# yum l i st i nstal l ed "kernel -*" kernel.x86_64 3.10.0-54.0.1.el7 kernel-devel.x86_64 3.10.0-54.0.1.el7 kernel-headers.x86_64 3.10.0-54.0.1.el7 @ rhel7/7.0 @ rhel7 @ rhel7/7.0 From the output, determine which packages need to be downloaded for the kernel upgrade. For a single processor system, the only required package is the kernel package. See Section 25.1, “ Overview of Kernel Packages” for descriptions of the different packages. 25.3. Downloading t he Upgraded Kernel There are several ways to determine if an updated kernel is available for the system. Security Errata — See https://access.redhat.com/site/security/updates/active/ for information on security errata, including kernel upgrades that fix security issues. Via Red Hat Network — D ownload and install the kernel RPM packages. Red Hat Network can download the latest kernel, upgrade the kernel on the system, create an initial RAM disk image if needed, and configure the boot loader to boot the new kernel. For more information, see the related documents located at https://access.redhat.com/documentation/en-US/. If Red Hat Network was used to download and install the updated kernel, follow the instructions in Section 25.5, “ Verifying the Initial RAM D isk Image” and Section 25.6, “ Verifying the Boot Loader” , only do not change the kernel to boot by default. Red Hat Network automatically changes the default kernel to the latest version. To install the kernel manually, continue to Section 25.4, “ Performing the Upgrade” . 25.4 . Performing t he Upgrade 4 80 Chapt er 2 5. Manually Upgrading t he Kernel 25.4 . Performing t he Upgrade After retrieving all of the necessary packages, it is time to upgrade the existing kernel. Important It is strongly recommended that you keep the old kernel in case there are problems with the new kernel. At a shell prompt, change to the directory that contains the kernel RPM packages. Use -i argument with the rpm command to keep the old kernel. D o not use the -U option, since it overwrites the currently installed kernel, which creates boot loader problems. For example: ~]# rpm -i vh kernel -kernel_version. arch. rpm The next step is to verify that the initial RAM disk image has been created. See Section 25.5, “ Verifying the Initial RAM D isk Image” for details. 25.5. Verifying t he Init ial RAM Disk Image The job of the initial RAM disk image is to preload the block device modules, such as for ID E, SCSI or RAID , so that the root file system, on which those modules normally reside, can then be accessed and mounted. On Red Hat Enterprise Linux 7 systems, whenever a new kernel is installed using either the Yu m, Packag eK it , or R PM package manager, the D racu t utility is always called by the installation scripts to create an initramfs (initial RAM disk image). On all architectures other than IBM eServer System i (see Section 25.5, “ Verifying the Initial RAM D isk Image and Kernel on IBM eServer System i” ), you can create an i ni tramfs by running the d racut command. However, you usually don't need to create an i ni tramfs manually: this step is automatically performed if the kernel and its associated packages are installed or upgraded from RPM packages distributed by Red Hat. You can verify that an i ni tramfs corresponding to your current kernel version exists and is specified correctly in the g rub. cfg configuration file by following this procedure: Pro ced u re 25.1. Verif yin g t h e In it ial R AM D isk Imag e 1. As ro o t, list the contents in the /bo o t/ directory and find the kernel (vml i nuz-kernel_version) and i ni tramfs-kernel_version with the latest (most recent) version number: Examp le 25.1. En su rin g t h at t h e kern el an d in it ramf s versio n s mat ch ~]# l s /bo o t/ config-3.10.0-67.el7.x86_64 config-3.10.0-78.el7.x86_64 efi grub grub2 initramfs-0-rescue-07f43f20a54c4ce8ada8b70d33fd001c.img initramfs-3.10.0-67.el7.x86_64.img initramfs-3.10.0-67.el7.x86_64kdump.img 4 81 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide initramfs-3.10.0-78.el7.x86_64.img initramfs-3.10.0-78.el7.x86_64kdump.img initrd-plymouth.img symvers-3.10.0-67.el7.x86_64.gz symvers-3.10.0-78.el7.x86_64.gz System.map-3.10.0-67.el7.x86_64 System.map-3.10.0-78.el7.x86_64 vmlinuz-0-rescue-07f43f20a54c4ce8ada8b70d33fd001c vmlinuz-3.10.0-67.el7.x86_64 vmlinuz-3.10.0-78.el7.x86_64 Example 25.1, “ Ensuring that the kernel and initramfs versions match” shows that: we have three kernels installed (or, more correctly, three kernel files are present in the /bo o t/ directory), the latest kernel is vml i nuz-3. 10 . 0 -78. el 7. x86 _6 4 , and an i ni tramfs file matching our kernel version, i ni tramfs-3. 10 . 0 78. el 7. x86 _6 4 kd ump. i mg , also exists. Important In the /bo o t/ directory you might find several i ni tramfs-kernel_versionkd ump. i mg files. These are special files created by the K d u mp mechanism for kernel debugging purposes, are not used to boot the system, and can safely be ignored. For more information on kd ump, see the Red Hat Enterprise Linux 7 Kernel Crash D ump Guide. 2. (Optional) If your i ni tramfs-kernel_version file does not match the version of the latest kernel in /bo o t/, or, in certain other situations, you might need to generate an i ni tramfs file with the D racu t utility. Simply invoking d racut as ro o t without options causes it to generate an i ni tramfs file in the /bo o t/ directory for the latest kernel present in that directory: ~]# d racut You must use the --fo rce option if you want d racut to overwrite an existing i ni tramfs (for example, if your i ni tramfs has become corrupt). Otherwise d racut will refuse to overwrite the existing i ni tramfs file: ~]# d racut Will not override existing initramfs (/boot/initramfs-3.10.078.el7.x86_64.img) without --force You can create an initramfs in the current directory by calling d racut initramfs_name kernel_version: ~]# d racut "i ni tramfs-$(uname -r). i mg " $(uname -r) If you need to specify specific kernel modules to be preloaded, add the names of those modules (minus any file name suffixes such as . ko ) inside the parentheses of the 4 82 Chapt er 2 5. Manually Upgrading t he Kernel ad d _d racutmo d ul es+ = "module [more_modules]" directive of the /etc/d racut. co nf configuration file. You can list the file contents of an i ni tramfs image file created by dracut by using the l si ni trd initramfs_file command: ~]# l si ni trd /bo o t/i ni tramfs-3. 10 . 0 -78. el 7. x86 _6 4 . i mg Image: /boot/initramfs-3.10.0-78.el7.x86_64.img: 11M ================================================================== ====== dracut-033-68.el7 ================================================================== ====== drwxr-xr-x 12 root drwxr-xr-x 2 root lrwxrwxrwx 1 root /usr/lib/systemd/systemd drwxr-xr-x 10 root drwxr-xr-x 2 root usr/lib/modprobe.d [output truncated] root root root 0 Feb 0 Feb 24 Feb root root 0 Feb 0 Feb 5 06:35 . 5 06:35 proc 5 06:35 init -> 5 06:35 etc 5 06:35 See man d racut and man d racut. co nf for more information on options and usage. 3. Examine the /bo o t/g rub2/g rub. cfg configuration file to ensure that an i ni tramfs-kernel_version. i mg file exists for the kernel version you are booting. For example: ~]# g rep i ni tramfs /bo o t/g rub2/g rub. cfg initrd16 /initramfs-3.10.0-123.el7.x86_64.img initrd16 /initramfs-0-rescue-6d547dbfd01c46f6a4c1baa8c4743f57.img See Section 25.6, “ Verifying the Boot Loader” for more information. Verifying t he Init ial RAM Disk Image and Kernel on IBM eServer Syst em i On IBM eServer System i machines, the initial RAM disk and kernel files are combined into a single file, which is created with the ad d R amD i sk command. This step is performed automatically if the kernel and its associated packages are installed or upgraded from the RPM packages distributed by Red Hat; thus, it does not need to be executed manually. To verify that it was created, run the following command as ro o t to make sure the /bo o t/vml i ni trd -kernel_version file already exists: l s -l /bo o t/ The kernel_version should match the version of the kernel just installed. 25.6. Verifying t he Boot Loader When you install a kernel using rpm, the kernel package creates an entry in the boot loader configuration file for that new kernel. However, rpm does not configure the new kernel to boot as the default kernel. You must do this manually when installing a new kernel with rpm. 4 83 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide It is always recommended to double-check the boot loader configuration file after installing a new kernel with rpm to ensure that the configuration is correct. Otherwise, the system might not be able to boot into Red Hat Enterprise Linux properly. If this happens, boot the system with the boot media created earlier and re-configure the boot loader. 4 84 Chapt er 2 6 . Working wit h Kernel Modules Chapter 26. Working with Kernel Modules The Linux kernel is modular, which means it can extend its capabilities through the use of dynamically-loaded kernel modules. A kernel module can provide: a device driver which adds support for new hardware; or, support for a file system such as btrfs or NFS. Like the kernel itself, modules can take parameters that customize their behavior, though the default parameters work well in most cases. User-space tools can list the modules currently loaded into a running kernel; query all available modules for available parameters and module-specific information; and load or unload (remove) modules dynamically into or from a running kernel. Many of these utilities, which are provided by the kmod package, take module dependencies into account when performing operations so that manual dependency-tracking is rarely necessary. On modern systems, kernel modules are automatically loaded by various mechanisms when the conditions call for it. However, there are occasions when it is necessary to load or unload modules manually, such as when one module is preferred over another although either could provide basic functionality, or when a module is misbehaving. This chapter explains how to: use the user-space kmo d utilities to display, query, load and unload kernel modules and their dependencies; set module parameters both dynamically on the command line and permanently so that you can customize the behavior of your kernel modules; and, load modules at boot time. Note In order to use the kernel module utilities described in this chapter, first ensure the kmod package is installed on your system by running, as root: ~]# yum i nstal l kmo d For more information on installing packages with Yum, see Section 7.2.4, “ Installing Packages” . 26.1. List ing Current ly-Loaded Modules You can list all kernel modules that are currently loaded into the kernel by running the l smo d command, for example: ~]$ l smo d Module tcp_lp bnep bluetooth rfkill Size 12663 19704 372662 26536 Used by 0 2 7 bnep 3 bluetooth 4 85 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide fuse 87661 3 ip6t_rpfilter 12546 1 ip6t_REJECT 12939 2 ipt_REJECT 12541 2 xt_conntrack 12760 7 ebtable_nat 12807 0 ebtable_broute 12731 0 bridge 110196 1 ebtable_broute stp 12976 1 bridge llc 14552 2 stp,bridge ebtable_filter 12827 0 ebtables 30913 3 ebtable_broute,ebtable_nat,ebtable_filter ip6table_nat 13015 1 nf_conntrack_ipv6 18738 5 nf_defrag_ipv6 34651 1 nf_conntrack_ipv6 nf_nat_ipv6 13279 1 ip6table_nat ip6table_mangle 12700 1 ip6table_security 12710 1 ip6table_raw 12683 1 ip6table_filter 12815 1 ip6_tables 27025 5 ip6table_filter,ip6table_mangle,ip6table_security,ip6table_nat,ip6table_ raw iptable_nat 13011 1 nf_conntrack_ipv4 14862 4 nf_defrag_ipv4 12729 1 nf_conntrack_ipv4 nf_nat_ipv4 13263 1 iptable_nat nf_nat 21798 4 nf_nat_ipv4,nf_nat_ipv6,ip6table_nat,iptable_nat [output truncated] Each row of l smo d output specifies: the name of a kernel module currently loaded in memory; the amount of memory it uses; and, the sum total of processes that are using the module and other modules which depend on it, followed by a list of the names of those modules, if there are any. Using this list, you can first unload all the modules depending the module you want to unload. For more information, see Section 26.4, “ Unloading a Module” . Finally, note that l smo d output is less verbose and considerably easier to read than the content of the /pro c/mo d ul es pseudo-file. 26.2. Displaying Informat ion About a Module You can display detailed information about a kernel module using the mo d i nfo module_name command. 4 86 Chapt er 2 6 . Working wit h Kernel Modules Note When entering the name of a kernel module as an argument to one of the kmo d utilities, do not append a . ko extension to the end of the name. Kernel module names do not have extensions; their corresponding files do. Examp le 26 .1. List in g in f o rmat io n ab o u t a kern el mo d u le wit h lsmo d To display information about the e10 0 0 e module, which is the Intel PRO/1000 network driver, enter the following command as ro o t: ~]# mo d i nfo e10 0 0 e filename: /lib/modules/3.10.0121.el7.x86_64/kernel/drivers/net/ethernet/intel/e1000e/e1000e.ko version: 2.3.2-k license: GPL description: Intel(R) PRO/1000 Network Driver author: Intel Corporation, srcversion: E9F7E754F6F3A1AD906634C alias: pci:v00008086d000015A3sv*sd*bc*sc*i* alias: pci:v00008086d000015A2sv*sd*bc*sc*i* [some alias lines omitted] alias: pci:v00008086d0000105Esv*sd*bc*sc*i* depends: ptp intree: Y vermagic: 3.10.0-121.el7.x86_64 SMP mod_unload modversions signer: Red Hat Enterprise Linux kernel signing key sig_key: 42:49:68:9E:EF:C7:7E:95:88:0B:13:DF:E4:67:EB:1B:7A:91:D1:08 sig_hashalgo: sha256 parm: debug:Debug level (0=none,...,16=all) (int) parm: copybreak:Maximum size of packet that is copied to a new buffer on receive (uint) parm: TxIntDelay:Transmit Interrupt Delay (array of int) parm: TxAbsIntDelay:Transmit Absolute Interrupt Delay (array of int) parm: RxIntDelay:Receive Interrupt Delay (array of int) parm: RxAbsIntDelay:Receive Absolute Interrupt Delay (array of int) parm: InterruptThrottleRate:Interrupt Throttling Rate (array of int) parm: IntMode:Interrupt Mode (array of int) parm: SmartPowerDownEnable:Enable PHY smart power down (array of int) parm: KumeranLockLoss:Enable Kumeran lock loss workaround (array of int) parm: WriteProtectNVM:Write-protect NVM [WARNING: disabling this can lead to corrupted NVM] (array of int) parm: CrcStripping:Enable CRC Stripping, disable if your BMC needs the CRC (array of int) Here are descriptions of a few of the fields in mo d i nfo output: 4 87 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide f ilen ame The absolute path to the . ko kernel object file. You can use mo d i nfo -n as a shortcut command for printing only the fi l ename field. d escrip t io n A short description of the module. You can use mo d i nfo -d as a shortcut command for printing only the description field. alias The al i as field appears as many times as there are aliases for a module, or is omitted entirely if there are none. d ep en d s This field contains a comma-separated list of all the modules this module depends on. Note If a module has no dependencies, the d epend s field may be omitted from the output. p arm Each parm field presents one module parameter in the form parameter_name: description, where: parameter_name is the exact syntax you should use when using it as a module parameter on the command line, or in an option line in a . co nf file in the /etc/mo d pro be. d / directory; and, description is a brief explanation of what the parameter does, along with an expectation for the type of value the parameter accepts (such as int, unit or array of int) in parentheses. Examp le 26 .2. List in g mo d u le p aramet ers You can list all parameters that the module supports by using the -p option. However, because useful value type information is omitted from mo d i nfo -p output, it is more useful to run: ~]# mo d i nfo e10 0 0 e | g rep "^parm" | so rt parm: copybreak:Maximum size of packet that is copied to a new buffer on receive (uint) parm: CrcStripping:Enable CRC Stripping, disable if your BMC needs the CRC (array of int) parm: debug:Debug level (0=none,...,16=all) (int) parm: InterruptThrottleRate:Interrupt Throttling Rate (array of int) parm: IntMode:Interrupt Mode (array of int) parm: KumeranLockLoss:Enable Kumeran lock loss workaround (array of int) parm: RxAbsIntDelay:Receive Absolute Interrupt Delay (array of int) 4 88 Chapt er 2 6 . Working wit h Kernel Modules parm: RxIntDelay:Receive Interrupt Delay (array of int) parm: SmartPowerDownEnable:Enable PHY smart power down (array of int) parm: TxAbsIntDelay:Transmit Absolute Interrupt Delay (array of int) parm: TxIntDelay:Transmit Interrupt Delay (array of int) parm: WriteProtectNVM:Write-protect NVM [WARNING: disabling this can lead to corrupted NVM] (array of int) 26.3. Loading a Module To load a kernel module, run mo d pro be module_name as ro o t. For example, to load the waco m module, run: ~]# mo d pro be waco m By default, mo d pro be attempts to load the module from /l i b/mo d ul es/kernel_version/kernel /d ri vers/. In this directory, each type of module has its own subdirectory, such as net/ and scsi /, for network and SCSI interface drivers respectively. Some modules have dependencies, which are other kernel modules that must be loaded before the module in question can be loaded. The mo d pro be command always takes dependencies into account when performing operations. When you ask mo d pro be to load a specific kernel module, it first examines the dependencies of that module, if there are any, and loads them if they are not already loaded into the kernel. mo d pro be resolves dependencies recursively: it will load all dependencies of dependencies, and so on, if necessary, thus ensuring that all dependencies are always met. You can use the -v (or --verbo se) option to cause mo d pro be to display detailed information about what it is doing, which can include loading module dependencies. Examp le 26 .3. mo d p ro b e - v sh o ws mo d u le d ep en d en cies as t h ey are lo ad ed You can load the Fi bre C hannel o ver Ethernet module verbosely by typing the following at a shell prompt: ~]# mo d pro be -v fco e insmod /lib/modules/3.10.0121.el7.x86_64/kernel/drivers/scsi/scsi_tgt.ko insmod /lib/modules/3.10.0121.el7.x86_64/kernel/drivers/scsi/scsi_transport_fc.ko insmod /lib/modules/3.10.0121.el7.x86_64/kernel/drivers/scsi/libfc/libfc.ko insmod /lib/modules/3.10.0121.el7.x86_64/kernel/drivers/scsi/fcoe/libfcoe.ko insmod /lib/modules/3.10.0121.el7.x86_64/kernel/drivers/scsi/fcoe/fcoe.ko In this example, you can see that mo d pro be loaded the scsi _tg t, scsi _transpo rt_fc, l i bfc and l i bfco e modules as dependencies before finally loading fco e. Also note that mo d pro be used the more primitive i nsmo d command to insert the modules into the running kernel. 4 89 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Important Although the i nsmo d command can also be used to load kernel modules, it does not resolve dependencies. Because of this, you should always load modules using mo d pro be instead. 26.4 . Unloading a Module You can unload a kernel module by running mo d pro be -r module_name as ro o t. For example, assuming that the waco m module is already loaded into the kernel, you can unload it by running: ~]# mo d pro be -r waco m However, this command will fail if a process is using: the waco m module; a module that waco m directly depends on, or; any module that waco m, through the dependency tree, depends on indirectly. See Section 26.1, “ Listing Currently-Loaded Modules” for more information about using l smo d to obtain the names of the modules which are preventing you from unloading a certain module. Examp le 26 .4 . U n lo ad in g a kern el mo d u le For example, if you want to unload the fi rewi re_o hci module, your terminal session might look similar to this: ~]# mo d i nfo -F d epend s fi rewi re_o hci firewire-core ~]# mo d i nfo -F d epend s fi rewi re_co re crc-itu-t ~]# mo d i nfo -F d epend s crc-i tu-t You have figured out the dependency tree (which does not branch in this example) for the loaded Firewire modules: fi rewi re_o hci depends on fi rewi re_co re, which itself depends on crci tu-t. You can unload fi rewi re_o hci using the mo d pro be -v -r module_name command, where -r is short for --remo ve and -v for --verbo se: ~]# mo d pro be -r -v fi rewi re_o hci rmmod firewire_ohci rmmod firewire_core rmmod crc_itu_t The output shows that modules are unloaded in the reverse order that they are loaded, given that no processes depend on any of the modules being unloaded. 4 90 Chapt er 2 6 . Working wit h Kernel Modules Important Although the rmmo d command can be used to unload kernel modules, it is recommended to use mo d pro be -r instead. 26.5. Set t ing Module Paramet ers Like the kernel itself, modules can also take parameters that change their behavior. Most of the time, the default ones work well, but occasionally it is necessary or desirable to set custom parameters for a module. Because parameters cannot be dynamically set for a module that is already loaded into a running kernel, there are two different methods for setting them. 1. You can unload all dependencies of the module you want to set parameters for, unload the module using mo d pro be -r, and then load it with mo d pro be along with a list of customized parameters. This method is often used when the module does not have many dependencies, or to test different combinations of parameters without making them persistent, and is the method covered in this section. 2. Alternatively, you can list the new parameters in an existing or newly created file in the /etc/mo d pro be. d / directory. This method makes the module parameters persistent by ensuring that they are set each time the module is loaded, such as after every reboot or mo d pro be command. This method is covered in Section 26.6, “ Persistent Module Loading” , though the following information is a prerequisite. Examp le 26 .5. Su p p lyin g o p t io n al p aramet ers wh en lo ad in g a kern el mo d u le You can use mo d pro be to load a kernel module with custom parameters using the following command line format: ~]# mo d pro be module_name [parameter= value] When loading a module with custom parameters on the command line, be aware of the following: You can enter multiple parameters and values by separating them with spaces. Some module parameters expect a list of comma-separated values as their argument. When entering the list of values, do not insert a space after each comma, or mo d pro be will incorrectly interpret the values following spaces as additional parameters. The mo d pro be command silently succeeds with an exit status of 0 if: it successfully loads the module, or the module is already loaded into the kernel. Thus, you must ensure that the module is not already loaded before attempting to load it with custom parameters. The mo d pro be command does not automatically reload the module, or alert you that it is already loaded. Here are the recommended steps for setting custom parameters and then loading a kernel module. This procedure illustrates the steps using the e10 0 0 e module, which is the network driver for Intel PRO/1000 network adapters, as an example: 4 91 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Pro ced u re 26 .1. Lo ad in g a K ern el Mo d u le wit h C u st o m Paramet ers 1. First, ensure the module is not already loaded into the kernel: ~]# l smo d | g rep e10 0 0 e ~]# Output would indicate that the module is already loaded into the kernel, in which case you must first unload it before proceeding. See Section 26.4, “ Unloading a Module” for instructions on safely unloading it. 2. Load the module and list all custom parameters after the module name. For example, if you wanted to load the Intel PRO/1000 network driver with the interrupt throttle rate set to 3000 interrupts per second for the first, second, and third instances of the driver, and turn on debug, you would run, as ro o t: ~]# mo d pro be e10 0 0 e InterruptT hro ttl eR ate= 30 0 0 ,30 0 0 ,30 0 0 d ebug = 1 This example illustrates passing multiple values to a single parameter by separating them with commas and omitting any spaces between them. 26.6. Persist ent Module Loading As shown in Example 26.1, “ Listing information about a kernel module with lsmod” , many kernel modules are loaded automatically at boot time. You can specify additional modules to be loaded by the systemd -mo d ul es-l o ad . servi ce daemon by creating a program. co nf file in the /etc/mo d ul es-l o ad . d / directory, where program is any descriptive name of your choice. The files in /etc/mo d ul es-l o ad . d / are text files that list the modules to be loaded, one per line. Examp le 26 .6 . A T ext File t o Lo ad a Mo d u le To create a file to load the vi rti o -net. ko module, create a file /etc/mo d ul esl o ad . d /vi rti o -net. co nf with the following content: # Load virtio-net.ko at boot virtio-net See the mo d ul es-l o ad . d (5) and systemd -mo d ul es-l o ad . servi ce(8) man pages for more information. 26.7. Signing Kernel Modules for Secure Boot Red Hat Enterprise Linux 7 includes support for the UEFI Secure Boot feature, which means that Red Hat Enterprise Linux 7 can be installed and run on systems where UEFI Secure Boot is enabled. [2] When Secure Boot is enabled, the EFI operating system boot loaders, the Red Hat Enterprise Linux kernel, and all kernel modules must be signed with a private key and authenticated with the corresponding public key. The Red Hat Enterprise Linux 7 distribution includes signed boot loaders, signed kernels, and signed kernel modules. In addition, the signed first-stage boot loader 4 92 Chapt er 2 6 . Working wit h Kernel Modules and the signed kernel include embedded Red Hat public keys. These signed executable binaries and embedded keys enable Red Hat Enterprise Linux 7 to install, boot, and run with the Microsoft UEFI Secure Boot CA keys that are provided by the UEFI firmware on systems that support UEFI Secure Boot. [3] The information provided in the following sections describes steps necessary to enable you to selfsign privately built kernel modules for use with Red Hat Enterprise Linux 7 on UEFI-based systems where Secure Boot is enabled. These sections also provide an overview of available options for getting your public key onto the target system where you want to deploy your kernel module. 26.7.1. Prerequisit es In order to enable signing of externally built modules, the tools listed in the following table are required to be installed on the system. T ab le 26 .1. R eq u ired T o o ls Tool Pro vid ed b y Packag e U sed o n Pu rp o se o penssl openssl Build system si g n-fi l e kernel-devel Build system perl perl Build system mo kuti l mokutil Target system keyctl keyutils Target system Generates public and private X.509 key pair Perl script used to sign kernel modules Perl interpreter used to run the signing script Optional tool used to manually enroll the public key Optional tool used to display public keys in the system key ring Note Note that the build system, where you build and sign your kernel module, does not need to have UEFI Secure Boot enabled and does not even need to be a UEFI-based system. 26.7.2. Kernel Module Aut hent icat ion In Red Hat Enterprise Linux 7, when a kernel module is loaded, the module's signature is checked using the public X.509 keys on the kernel's system key ring, excluding those keys that are on the kernel's system black list key ring. 2 6 .7 .2 .1 . So urce s Fo r Public Ke ys Use d T o Aut he nt icat e Ke rne l Mo dule s D uring boot, the kernel loads X.509 keys into the system key ring or the system black list key ring from a set of persistent key stores as shown in Table 26.2, “ Sources For System Key Rings” T ab le 26 .2. So u rces Fo r Syst em K ey R in g s 4 93 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide So u rce o f X.509 K eys U ser Ab ilit y t o Ad d K eys U EFI Secu re B o o t St at e K eys Lo ad ed D u rin g Boot Embedded in kernel UEFI Secure Boot " db" No Limited UEFI Secure Boot " dbx" Limited Embedded in shi m. efi boot loader Machine Owner Key (MOK) list No Not enabled Enabled Not enabled Enabled Not enabled Enabled . system_keyri ng No . system_keyri ng No . system_keyri ng No . system_keyri ng Not enabled Enabled No . system_keyri ng Yes Note that if the system is not UEFI-based or if UEFI Secure Boot is not enabled, then only the keys that are embedded in the kernel are loaded onto the system key ring and you have no ability to augment that set of keys without rebuilding the kernel. The system black list key ring is a list of X.509 keys which have been revoked. If your module is signed by a key on the black list then it will fail authentication even if your public key is in the system key ring. You can display information about the keys on the system key rings using the keyctl utility. The following is abbreviated example output from a Red Hat Enterprise Linux 7 system where UEFI Secure Boot is not enabled. ~]# keyctl l i st %: . system_keyri ng 3 keys in keyring: ...asymmetric: Red Hat Enterprise Linux Driver Update Program (key 3): bf57f3e87... ...asymmetric: Red Hat Enterprise Linux kernel signing key: 4249689eefc77e95880b... ...asymmetric: Red Hat Enterprise Linux kpatch signing key: 4d38fd864ebe18c5f0b7... The following is abbreviated example output from a Red Hat Enterprise Linux 7 system where UEFI Secure Boot is enabled. ~]# keyctl l i st %: . system_keyri ng 6 keys in keyring: ...asymmetric: Red Hat Enterprise Linux Driver Update Program (key 3): bf57f3e87... ...asymmetric: Red Hat Secure Boot (CA key 1): 4016841644ce3a810408050766e8f8a29... ...asymmetric: Microsoft Corporation UEFI CA 2011: 13adbf4309bd82709c8cd54f316ed... ...asymmetric: Microsoft Windows Production PCA 2011: a92902398e16c49778cd90f99e... ...asymmetric: Red Hat Enterprise Linux kernel signing key: 4249689eefc77e95880b... ...asymmetric: Red Hat Enterprise Linux kpatch signing key: 4d38fd864ebe18c5f0b7... The above output shows the addition of two keys from the UEFI Secure Boot " db" keys plus the R ed Hat Secure Bo o t (C A key 1) which is embedded in the shi m. efi boot loader. You can also look for the kernel console messages that identify the keys with an UEFI Secure Boot related source, that is UEFI Secure Boot db, embedded shim, and MOK list. 4 94 Chapt er 2 6 . Working wit h Kernel Modules ~]# d mesg | g rep ' EFI: Lo ad ed cert' [5.160660] EFI: Loaded cert 'Microsoft Windows Production PCA 2011: a9290239... [5.160674] EFI: Loaded cert 'Microsoft Corporation UEFI CA 2011: 13adbf4309b... [5.165794] EFI: Loaded cert 'Red Hat Secure Boot (CA key 1): 4016841644ce3a8... 2 6 .7 .2 .2 . Ke rne l Mo dule Aut he nt icat io n Re quire m e nt s If UEFI Secure Boot is enabled or if the mo d ul e. si g _enfo rce kernel parameter has been specified, then only signed kernel modules that are authenticated using a key on the system key ring can be successfully loaded. [4] If UEFI Secure Boot is disabled and if the mo d ul e. si g _enfo rce kernel parameter has not been specified, then unsigned kernel modules and signed kernel modules without a public key can be successfully loaded. This is summarized in Table 26.3, “ Kernel Module Authentication Requirements for Loading” . T ab le 26 .3. K ern el Mo d u le Au t h en t icat io n R eq u iremen t s f o r Lo ad in g Mo d u le Sig n ed Pu b lic K ey Fo u n d an d Sig n at u re Valid U EFI Secu re B o o t St at e mo d u le.sig _ en f o rce Mo d u le Lo ad K ern el T ain t ed Unsigned - Not enabled Not enabled Enabled Not enabled Not enabled Enabled Not enabled Not enabled Enabled Not enabled Enabled Not enabled Enabled Not enabled Enabled - Succeeds Fails Fails Succeeds Fails Fails Succeeds Succeeds Succeeds Yes Signed No Signed Yes Yes No No No Subsequent sections will describe how to generate a public and private X.509 key pair, how to use the private key to sign a kernel module, and how to enroll the public key into a source for the system key ring. 26.7.3. Generat ing a Public and Privat e X.509 Key Pair You need to generate a public and private X.509 key pair that will be used to sign a kernel module after it has been built. The corresponding public key will be used to authenticate the kernel module when it is loaded. 1. The o penssl tool can be used to generate a key pair that satisfies the requirements for kernel module signing in Red Hat Enterprise Linux 7. Some of the parameters for this key generation request are best specified with a configuration file; follow the example below to create your own configuration file. ~]# cat << EO F > configuration_file. co nfi g [ req ] default_bits = 4096 distinguished_name = req_distinguished_name prompt = no 4 95 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide string_mask = utf8only x509_extensions = myexts [ req_distinguished_name ] O = Organization CN = Organization signing key emailAddress = E-mail address [ myexts ] basicConstraints=critical,CA:FALSE keyUsage=digitalSignature subjectKeyIdentifier=hash authorityKeyIdentifier=keyid EOF 2. After you have created the configuration file, you can create an X.509 public and private key pair. The public key will be written to the public_key. d er file and the private key will be written to the private_key. pri v file. ~]# o penssl req -x50 9 -new -no d es -utf8 -sha256 -d ays 36 50 0 \ > batch -co nfi g configuration_file. co nfi g -o utfo rm D ER \ > -o ut public_key. d er \ > -keyo ut private_key. pri v 3. Enroll your public key on all systems where you want to authenticate and load your kernel module. Warning Take proper care to guard the contents of your private key. In the wrong hands, the key could be used to compromise any system which has your public key. 26.7.4 . Enrolling Public Key on T arget Syst em When Red Hat Enterprise Linux 7 boots on a UEFI-based system with Secure Boot enabled, all keys that are in the Secure Boot db key database, but not in the dbx database of revoked keys, are loaded onto the system keyring by the kernel. The system keyring is used to authenticate kernel modules. 2 6 .7 .4 .1 . Fact o ry Firm ware Im age Including Public Ke y To facilitate authentication of your kernel module on your systems, consider requesting your system vendor to incorporate your public key into the UEFI Secure Boot key database in their factory firmware image. 2 6 .7 .4 .2 . Exe cut able Ke y Enro llm e nt Im age Adding Public Ke y It is possible to add a key to an existing populated and active Secure Boot key database. This can be done by writing and providing an EFI executable enrollment image. Such an enrollment image contains a properly formed request to append a key to the Secure Boot key database. This request must include data that is properly signed by the private key that corresponds to a public key that is already in the system's Secure Boot Key Exchange Key (KEK) database. Additionally, this EFI image must be signed by a private key that corresponds to a public key that is already in the key database. 4 96 Chapt er 2 6 . Working wit h Kernel Modules It is also possible to write an enrollment image that runs under Red Hat Enterprise Linux 7. However, the Red Hat Enterprise Linux 7 image must be properly signed by a private key that corresponds to a public key that is already in the KEK database. The construction of either type of key enrollment images requires assistance from the platform vendor. 2 6 .7 .4 .3. Syst e m Adm inist rat o r Manually Adding Public Ke y t o t he MOK List The Machine Owner Key (MOK) facility is a feature that is supported by Red Hat Enterprise Linux 7 and can be used to augment the UEFI Secure Boot key database. When Red Hat Enterprise Linux 7 boots on a UEFI-enabled system with Secure Boot enabled, the keys on the MOK list are also added to the system keyring in addition to the keys from the key database. The MOK list keys are also stored persistently and securely in the same fashion as the Secure Boot key database keys, but these are two separate facilities. The MOK facility is supported by shim.efi, MokManager.efi, grubx64.efi, and the Red Hat Enterprise Linux 7 mo kuti l utility. The major capability provided by the MOK facility is the ability to add public keys to the MOK list without needing to have the key chain back to another key that is already in the KEK database. However, enrolling a MOK key requires manual interaction by a physically present user at the UEFI system console on each target system. Nevertheless, the MOK facility provides an excellent method for testing newly generated key pairs and testing kernel modules signed with them. Follow these steps to add your public key to the MOK list: 1. Request addition of your public key to the MOK list using a Red Hat Enterprise Linux 7 userspace utility: ~]# mo kuti l --i mpo rt my_si g ni ng _key_pub. d er You will be asked to enter and confirm a password for this MOK enrollment request. 2. Reboot the machine. 3. The pending MOK key enrollment request will be noticed by shi m. efi and it will launch Mo kManag er. efi to allow you to complete the enrollment from the UEFI console. You will need to enter the password you previously associated with this request and confirm the enrollment. Your public key is added to the MOK list, which is persistent. Once a key is on the MOK list, it will be automatically propagated to the system key ring on this and subsequent boots when UEFI Secure Boot is enabled. 26.7.5. Signing Kernel Module wit h t he Privat e Key There are no extra steps required to prepare your kernel module for signing. You build your kernel module normally. Assuming an appropriate Makefile and corresponding sources, follow these steps to build your module and sign it: 1. Build your my_mo d ul e. ko module the standard way: ~]# make -C /usr/src/kernel s/$(uname -r) M= $P WD mo d ul es 2. Sign your kernel module with your private key. This is done with a Perl script. Note that the script requires that you provide both the files that contain your private and the public key as well as the kernel module file that you want to sign. 4 97 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide ~]# perl /usr/src/kernel s/$(uname -r)/scri pts/si g n-fi l e \ > sha256 \ > my_si g ni ng _key. pri v \ > my_si g ni ng _key_pub. d er \ > my_mo d ul e. ko Your kernel module is in ELF image format and this script computes and appends the signature directly to the ELF image in your my_mo d ul e. ko file. The mo d i nfo utility can be used to display information about the kernel module's signature, if it is present. For information on using the utility, see Section 26.2, “ D isplaying Information About a Module” . Note that this appended signature is not contained in an ELF image section and is not a formal part of the ELF image. Therefore, tools such as read el f will not be able to display the signature on your kernel module. Your kernel module is now ready for loading. Note that your signed kernel module is also loadable on systems where UEFI Secure Boot is disabled or on a non-UEFI system. That means you do not need to provide both a signed and unsigned version of your kernel module. 26.7.6. Loading Signed Kernel Module Once your public key is enrolled and is in the system keyring, the normal kernel module loading mechanisms will work transparently. In the following example, you will use mo kuti l to add your public key to the MOK list and you will manually load your kernel module with mo d pro be. 1. Optionally, you can verify that your kernel module will not load before you have enrolled your public key. First, verify what keys have been added to the system key ring on the current boot by running the keyctl l i st %: . system_keyri ng as root. Since your public key has not been enrolled yet, it should not be displayed in the output of the command. 2. Request enrollment of your public key. ~]# mo kuti l --i mpo rt my_signing_key_pub. d er 3. Reboot, and complete the enrollment at the UEFI console. ~]# rebo o t 4. After the system reboots, verify the keys on the system key ring again. ~]# keyctl l i st %: . system_keyri ng 5. You should now be able to load your kernel module successfully. ~]# mo d pro be -v my_module insmod /lib/modules/3.10.0-123.el7.x86_64/extra/my_module.ko ~]# l smo d | g rep my_module my_module 12425 0 26.8. Addit ional Resources For more information on kernel modules and their utilities, see the following resources. Manual Page Document at ion 4 98 Chapt er 2 6 . Working wit h Kernel Modules l smo d (8) — The manual page for the l smo d command. mo d i nfo (8) — The manual page for the mo d i nfo command. mo d pro be(8) — The manual page for the mo d pro be command. rmmo d (8) — The manual page for the rmmo d command. ethto o l (8) — The manual page for the ethto o l command. mi i -to o l (8) — The manual page for the mi i -to o l command. Inst allable and Ext ernal Document at ion /usr/share/d o c/kernel -d o c-kernel_version/D o cumentati o n/ — This directory, which is provided by the kernel-doc package, contains information on the kernel, kernel modules, and their respective parameters. Before accessing the kernel documentation, you must run the following command as ro o t: ~]# yum i nstal l kernel -d o c Linux Loadable Kernel Module HOWTO — The Linux Loadable Kernel Module HOWTO from the Linux D ocumentation Project contains further information on working with kernel modules. [2] Red Hat Enterp ris e Linux 7 d o es no t req uire the us e o f Sec ure Bo o t o n UEFI s ys tems . [3] No t all UEFI-b as ed s ys tems inc lud e s up p o rt fo r Sec ure Bo o t. [4] Pro vid ed that the p ub lic key is no t o n the s ys tem b lac k lis t key ring . 4 99 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide RPM The RPM Package Manager (R PM) is an open packaging system that runs on Red Hat Enterprise Linux as well as other Linux and UNIX systems. Red Hat and the Fedora Project encourage other vendors to use R PM for their own products. R PM is distributed under the terms of the GPL (GNU General Public License). The R PM Packag e Man ag er only works with packages built in the RPM format. R PM itself is provided as the pre-installed rpm package. For the end user, R PM makes system updates easy. Installing, uninstalling, and upgrading R PM packages can be accomplished with short commands. R PM maintains a database of installed packages and their files, so you can invoke powerful queries and verifications on your system. There are several applications, such as Yu m or Packag eK it , that can make working with packages in the R PM format even easier. Warning For most package-management tasks, the Yu m package manager offers equal and often greater capabilities and utility than R PM. Yu m also performs and tracks complicated systemdependency resolutions. Yu m maintains the system integrity and forces a system integrity check if packages are installed or removed using another application, such as R PM, instead of Yu m. For these reasons, it is highly recommended that you use Yu m instead of R PM whenever possible to perform package-management tasks. See Chapter 7, Yum. If you prefer a graphical interface, you can use the Packag eK it GUI application, which uses Yu m as its back end, to manage your system's packages. D uring upgrades, R PM handles configuration files carefully, so that you never lose your customizations — something that you cannot accomplish with regular . tar. g z files. For the developer, R PM enables software source code to be packaged into source and binary packages for end users. This process is quite simple and is driven from a single file and optional patches that you create. This clear delineation between pristine sources and your patches along with build instructions eases the maintenance of the package as new versions of the software are released. Note Because R PM can make changes to the system itself, performing operations like installing, upgrading, downgrading, and uninstalling binary packages system-wide requires ro o t privileges in most cases. A.1. RPM Design Goals To understand how to use R PM, it is helpful to understand the design goals of R PM: U p g rad ab ilit y With R PM, you can upgrade individual components of your system without a complete reinstallation. When you get a new release of an operating system based on R PM, such as Red Hat Enterprise Linux, you do not need to reinstall a fresh copy of the operating system 500 RPM on your machine (as you might need to with operating systems based on other packaging systems). R PM allows for intelligent, fully-automated, in-place upgrades of your system. In addition, configuration files in packages are preserved across upgrades, so you do not lose your customizations. There are no special upgrade files needed to upgrade a package because the same R PM file is used to both install and upgrade the package on the system. Po werf u l Q u eryin g R PM is designed to provide powerful querying options. You can perform searches on your copy of the database for packages or even just certain files. You can also easily find out what package a file belongs to and where the package came from. The files an R PM package contains are in a compressed archive, with a custom binary header containing useful information about the package and its contents, allowing you to query individual packages quickly and easily. Syst em Verif icat io n Another powerful R PM feature is the ability to verify packages. It allows you to verify that the files installed on the system are the same as the ones supplied by a given package. If an inconsistency is detected, R PM notifies you, and you can reinstall the package if necessary. Any configuration files that you modified are preserved during reinstallation. Prist in e So u rces A crucial design goal was to allow the use of pristine software sources, as distributed by the original authors of the software. With R PM, you have the pristine sources along with any patches that were used, plus complete build instructions. This is an important advantage for several reasons. For example, if a new version of a program is released, you do not necessarily have to start from scratch to get it to compile. You can look at the patch to see what you might need to do. All the compiled-in defaults, and all of the changes that were made to get the software to build properly, are easily visible using this technique. The goal of keeping sources pristine may seem important only for developers, but it results in higher quality software for end users. A.2. Using RPM R PM has five basic modes of operation (excluding package building): installing, uninstalling, upgrading, querying, and verifying. This section contains an overview of each mode. For complete details and options, try rpm --hel p or see rpm(8). Also, see Section A.5, “ Additional Resources” for more information on R PM. A.2.1. Inst alling and Upgrading Packages R PM packages typically have file names in the following form: package_name-version-release-operating_system-CPU_architecture.rpm For example the tree-1. 6 . 0 -10 . el 7. x86 _6 4 . rpm file name includes the package name (tree), version (1. 6 . 0 ), release (10 ), operating system major version (el 7) and CPU architecture (x86 _6 4 ). 501 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Important When installing a package, ensure it is compatible with your operating system and processor architecture. This can usually be determined by checking the package name. For example, the file name of an R PM package compiled for the AMD 64/Intel 64 computer architectures ends with x86 _6 4 . rpm. The -U (or --upg rad e) option has two functions, it can be used to: upgrade an existing package on the system to a newer version, or install a package if an older version is not already installed. The rpm -U package.rpm command is therefore able to either upgrade or install, depending on the presence of an older version of package.rpm on the system. Assuming the tree-1. 6 . 0 -10 . el 7. x86 _6 4 . rpm package is in the current directory, log in as ro o t and type the following command at a shell prompt to either upgrade or install the tree package: ~]# rpm -Uvh tree-1. 6 . 0 -10 . el 7. x86 _6 4 . rpm The -v and -h options (which are combined with -U) cause rpm to print a more verbose output and display a progress meter using hash signs. If the upgrade or installation is successful, the following output is displayed: Preparing... Updating / installing... 1:tree-1.6.0-10.el7 ################################# [100%] ################################# [100%] Warning rpm provides two different options for installing packages: the aforementioned -U option (which historically stands for upgrade), and the -i option (which historically stands for install). Because the -U option includes both install and upgrade functions, the use of rpm -Uvh with all packages, excep t kernel packages, is recommended. You should always use the -i option to install a new kernel package instead of upgrading it. This is because using the -U option to upgrade a kernel package removes the previous (older) kernel package, which could render the system unable to boot if there is a problem with the new kernel. Therefore, use the rpm -i kernel_package command to install a new kernel without replacing any older kernel packages. For more information on installing kernel packages, see Chapter 25, Manually Upgrading the Kernel. The signature of a package is checked automatically when installing or upgrading a package. The signature confirms that the package was signed by an authorized party. If the verification of the signature fails, an error message is displayed. If you do not have the appropriate key installed to verify the signature, the message contains the word NO KEY : 502 RPM warning: tree-1.6.0-10.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 431d51: NOKEY See Section A.3.2, “ Checking Package Signatures” for more information on checking package signatures. A.2 .1 .1 . Re placing Alre ady-Inst alle d Package s If a package of the same name and version is already installed, the following output is displayed: Preparing... ########################################### [100%] package tree-1.6.0-10.el7.x86_64 is already installed To install the package anyway, use the --repl acepkg s option, which tells R PM to ignore the error: ~]# rpm -Uvh --repl acepkg s tree-1. 6 . 0 -10 . el 7. x86 _6 4 . rpm This option is helpful if files installed from the package were deleted or if you want the original configuration files to be installed. If you attempt an upgrade to an older version of a package (that is, if a newer version of the package is already installed), R PM informs you that a newer version is already installed. To force R PM to perform the downgrade, use the --o l d packag e option: rpm -Uvh --o l d packag e older_package.rpm A.2 .1 .2 . Re so lving File Co nflict s If you attempt to install a package that contains a file that has already been installed by another package, a conflict message is displayed. To make R PM ignore this error, use the -repl acefi l es option: rpm -Uvh --repl acefi l es package.rpm A.2 .1 .3. Sat isfying Unre so lve d De pe nde ncie s R PM packages sometimes depend on other packages, which means that they require other packages to be installed to run properly. If you try to install a package that has an unresolved dependency, a message about a failed dependency is displayed. Find the suggested package(s) on the Red Hat Enterprise Linux installation media or on one of the active Red Hat Enterprise Linux mirrors and add it to the installation command. To determine which package contains the required file, use the --whatpro vi d es option: rpm -q --whatpro vi d es "required_file" If the package that contains required_file is in the R PM database, the name of the package is displayed. 503 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Warning Although you can force rpm to install a package that has an unresolved dependency (using the --no d eps option), this is not recommended and will usually result in the installed software failing to run. Installing packages with --no d eps can cause applications to misbehave or terminate unexpectedly. It can also cause serious package-management problems or system failure. For these reasons, heed the warnings about missing dependencies. The Yu m package manager performs automatic dependency resolution and fetches dependencies from on-line repositories. A.2 .1 .4 . Pre se rving Change s in Co nfigurat io n File s Because R PM performs intelligent upgrading of packages with configuration files, you may see the following message: saving /etc/configuration_file.conf as /etc/configuration_file.conf.rpmsave This message means that the changes you made to the configuration file may not be forwardcompatible with the new configuration file in the package, so R PM saved your original file and installed a new one. You should investigate the differences between the two configuration files and resolve them as soon as possible to ensure that your system continues to function properly. Alternatively, R PM may save the package's new configuration file as, for example, configuration_file.conf. rpmnew and leave the configuration file you modified untouched. You should still resolve any conflicts between your modified configuration file and the new one, usually by merging changes from the old one to the new one, for example using the d i ff program. A.2.2. Uninst alling Packages Uninstalling a package is just as simple as installing one. Type the following command at a shell prompt as ro o t: rpm -e package Note Note that the command expects only the package name, not the name of the original package file. If you attempt to uninstall a package using the rpm -e command and provide the original full file name, you receive a package-name error. You can encounter dependency errors when uninstalling a package if another installed package depends on the one you are trying to remove. For example: ~]# rpm -e g ho stscri pt error: Failed dependencies: ghostscript is needed by (installed) ghostscript-cups-9.0716.el7.x86_64 ghostscript is needed by (installed) foomatic-4.0.9-6.el7.x86_64 libgs.so.9()(64bit) is needed by (installed) libspectre-0.2.7- 504 RPM 4.el7.x86_64 libijs-0.35.so()(64bit) is needed by (installed) gutenprint5.2.9-15.el7.x86_64 libijs-0.35.so()(64bit) is needed by (installed) cups-filters1.0.35-15.el7.x86_64 Warning Although you can force rpm to uninstall a package that has unresolved dependencies (using the --no d eps option), this is not recommended. Removing packages with --no d eps can cause applications from the packages whose dependencies are removed to misbehave or terminate unexpectedly. It can also cause serious package-management problems or system failure. For these reasons, heed the warnings about failed dependencies. A.2.3. Freshening Packages Freshening is similar to upgrading, except that only installed packages are upgraded. Type the following command at a shell prompt as ro o t: rpm -Fvh package.rpm The -F (or --freshen) option compares the versions of the packages specified on the command line with the versions of packages that are already installed on the system. When a newer version of an already-installed package is processed by the --freshen option, it is upgraded to the newer version. However, the --freshen option does not install a package if no previously-installed package of the same name exists. This differs from regular upgrading, as an upgrade installs all specified packages regardless of whether or not older versions of the packages are already installed. Freshening works for single packages or package groups. For example, freshening can help if you download a large number of different packages, and you only want to upgrade those packages that are already installed on the system. In this case, issue the following command with the *. rpm global expression: ~]# rpm -Fvh *. rpm R PM then automatically upgrades only those packages that are already installed. A.2.4 . Querying Packages The R PM database stores information about all R PM packages installed on the system. It is stored in the /var/l i b/rpm/ directory and is used for many things, including querying what packages are installed, what version each package is, and for calculating changes to files in packages since their installation. To query this database, use the rpm command with the -q (or --q uery) option: rpm -q package_name This command displays the package name, version, and release number of the installed package package_name. For example: ~]$ rpm -q tree tree-1.6.0-10.el7.x86_64 505 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide See the P ackag e Sel ecti o n O pti o ns subheading in the rpm(8) manual page for a list of options that can be used to further refine or qualify your query. Use options listed below the P ackag e Q uery O pti o ns subheading to specify what information to display about the queried packages. A.2.5. Verifying Packages Verifying a package is comparing information about files on the system installed from a package with the same information from the original package. Among other parameters, verifying compares the file size, MD 5 sum, permissions, type, owner, and the group of each file. Use the rpm command with the -V (or --veri fy) option to verify packages. For example: ~]$ rpm -V tree See the P ackag e Sel ecti o n O pti o ns subheading in the rpm(8) manual page for a list of options that can be used to further refine or qualify your query. Use options listed below the Veri fy O pti o ns subheading to specify what characteristics to verify in the queried packages. If everything verifies properly, there is no output. If there are any discrepancies, they are displayed. The output consists of lines similar to these: ~]# rpm -V abrt S.5....T. c /etc/abrt/abrt.conf .M....... /var/spool/abrt-upload The format of the output is a string of nine characters followed by an optional attribute marker and the name of the processed file. The first nine characters are the results of tests performed on the file. Each test is the comparison of one attribute of the file to the value of that attribute as recorded in the R PM database. A single period (. ) means the test passed, and the question-mark character (?) signifies that the test could not be performed. The following table lists symbols that denote specific discrepancies: T ab le A.1. R PM Verif icat io n Symb o ls Symb o l D escrip t io n S M 5 D L U G T P file size differs mode differs (includes permissions and file type) digest (formerly MD 5 sum) differs device major/minor number mismatch readLink(2) path mismatch user ownership differs group ownership differs mtime differs capabilities differ The attribute marker, if present, describes the purpose of the given file. The following table lists the available attribute markers: T ab le A.2. R PM Verif icat io n Symb o ls 506 RPM Marker D escrip t io n c d l r configuration file documentation file license file readme file If you see any output, use your best judgment to determine if you should remove the package, reinstall it, or fix the problem in another way. A.3. Finding and Verifying RPM Packages Before using any R PM packages, you must know where to find them and be able to verify if you can trust them. A.3.1. Finding RPM Packages Although there are many R PM repositories on the Internet, for security and compatibility reasons, you should consider installing only official Red Hat-provided RPM packages. The following is a list of sources for R PM packages: Official Red Hat Enterprise Linux installation media. Official R PM repositories provided with the Yu m package manager. See Chapter 7, Yum for details on how to use the official Red Hat Enterprise Linux package repositories. The Red Hat Errata Page, available on the Customer Portal at https://rhn.redhat.com/rhn/errata/RelevantErrata.do. Extra Packages for Enterprise Linux (EPEL) is a community effort to provide a repository with high-quality add-on packages for Red Hat Enterprise Linux. See http://fedoraproject.org/wiki/EPEL for details on EPEL R PM packages. Unofficial, third-party repositories not affiliated with Red Hat also provide RPM packages. Important When considering third-party repositories for use with your Red Hat Enterprise Linux system, pay close attention to the repository's web site with regard to package compatibility before adding the repository as a package source. Alternate package repositories may offer different, incompatible versions of the same software, including packages already included in the Red Hat Enterprise Linux repositories. A.3.2. Checking Package Signat ures R PM packages can be signed using G N U Privacy G u ard (or G PG ), which helps you make certain that downloaded packages are trustworthy. G PG is a tool for secure communication. With G PG , you can authenticate the validity of documents and encrypt or decrypt data. To verify that a package has not been corrupted or tampered with, check its G PG signature by using the rpmkeys command with the -K (or --checksi g ) option: rpmkeys -K package.rpm 507 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Note that the Yu m package manager performs automatic checking of G PG signatures during installations and upgrades. G PG is installed by default, as well as a set of Red Hat keys for verifying packages. To import additional keys for use with R PM, see Section A.3.2.1, “ Importing GPG Keys” . A.3.2 .1 . Im po rt ing GPG Ke ys To verify Red Hat packages, a Red Hat G PG key needs to be installed. A set of basic keys is installed by default. To view a list of installed keys, execute the following command at a shell prompt: ~]$ rpm -q a g pg -pubkey* To display details about a specific key, use rpm -q i followed by the output from the previous command. For example: ~]$ rpm -q i g pg -pubkey-fd 4 31d 51-4 ae0 4 9 3b Use the rpmkeys command with the --i mpo rt option to install a new key for use with R PM. The default location for storing R PM GPG keys is the /etc/pki /rpm-g pg / directory. To import new keys, use a command like the following as ro o t: ~]# rpmkeys --i mpo rt /etc/pki /rpm-g pg /R P M-G P G -KEY -red hat-rel ease See the Product Signing (GPG) Keys article on the Red Hat Customer Portal for additional information about Red Hat package-signing practices. A.4 . Common Examples of RPM Usage R PM is a useful tool for both managing your system and diagnosing and fixing problems. See the following examples for an overview of some of the most-used options. To verify your entire system and see what files are missing, issue the following command as ro o t: rpm -Va If some files are missing or appear corrupted, consider reinstalling relevant packages. To determine which package owns a file, enter: rpm -q f file To verify the package that owns a particular file, enter as ro o t: rpm -Vf file To locate documentation files that are a part of a package to which a file belongs, enter: rpm -q d f file To find information about a (non-installed) package file, use the following command: 508 RPM rpm -q i p package.rpm To list files contained in a package, use: rpm -q l p package.rpm See the rpm(8) manual page for more options. A.5. Addit ional Resources R PM is a complex utility with many options and methods for querying, installing, upgrading, and removing packages. See the following resources to learn more about R PM. Inst alled Document at ion rpm --hel p — This command displays a quick reference of R PM parameters. rpm(8) — The R PM manual page offers an overview of all available R PM parameters. Online Document at ion Red Hat Enterprise Linux 7 Security Guide — The Security Guide for Red Hat Enterprise Linux 7 documents how to keep your system up-to-date using the Yu m package manager and how to verify and install downloaded packages. The R PM website — http://www.rpm.org/ The R PM mailing list — http://lists.rpm.org/mailman/listinfo/rpm-list See Also Chapter 7, Yum describes how to use the Yu m package manager to search, install, update, and uninstall packages on the command line. 509 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide Revision History R evisio n 0.14 - 0.3 Fri Ap r 3 2015 St ep h en Wad eley Added Registering the System and Managing Subscriptions, Accessing Support Using the Red Hat Support Tool, updated Viewing and Managing Log Files. R evisio n 0.13- 2 Version for 7.1 GA release. T u e Feb 24 2015 St ep h en Wad eley R evisio n 0.12- 0.6 Improved TigerVNC. T u e N o v 18 2014 St ep h en Wad eley R evisio n 0.12- 0.4 Mo n N o v 10 2014 St ep h en Wad eley Improved Yum, Managing Services with systemd, OpenLDAP, Viewing and Managing Log Files, OProfile, and Working with the GRUB 2 Boot Loader. R evisio n 0.12- 0 T u e 19 Au g 2014 St ep h en Wad eley Red Hat Enterprise Linux 7.0 GA release of the System Administrator's Guide. B.1. Acknowledgment s Certain portions of this text first appeared in the Red Hat Enterprise Linux 6 Deployment Guide, copyright © 2014 Red Hat, Inc., available at https://access.redhat.com/documentation/enUS/Red_Hat_Enterprise_Linux/6/html/D eployment_Guide/index.html. Section 18.6, “ Monitoring Performance with Net-SNMP” is based on an article written by Michael Solberg. Index Symbols .f et ch mailrc, Fet ch mail C o n f ig u rat io n O p t io n s - server options, Server Options - user options, User Options .p ro cmailrc, Pro cmail C o n f ig u rat io n /d ev/o p ro f ile/, U n d erst an d in g t h e /d ev/o p ro f ile/ d irect o ry /var/sp o o l/an acro n , C o n f ig u rin g An acro n Jo b s /var/sp o o l/cro n , C o n f ig u rin g C ro n Jo b s ( see O Pro f ile) A AB R T , In t ro d u ct io n t o AB R T - (see also abrtd) - (see also Bugzilla) - (see also Red Hat Technical Support) - additional resources, Additional Resources - autoreporting, Setting Up Automatic Reporting 510 Revision Hist ory - CLI, Using the Command Line Tool configuring, Configuring ABRT configuring events, Configuring Events crash detection, Introduction to ABRT creating events, Creating Custom Events GUI, Using the GUI installing, Installing ABRT and Starting its Services introducing, Introduction to ABRT problems - detecting, D etecting Software Problems - handling of, Handling D etected Problems - supported, D etecting Software Problems - standard events, Configuring Events - starting, Installing ABRT and Starting its Services, Starting the ABRT Services - testing, Testing ABRT Crash D etection AB R T C LI - installing, Installing ABRT for the Command Line AB R T G U I - installing, Installing the ABRT GUI AB R T T o o ls - installing, Installing Supplementary ABRT Tools ab rt d - additional resources, Additional Resources restarting, Starting the ABRT Services starting, Installing ABRT and Starting its Services, Starting the ABRT Services status, Starting the ABRT Services testing, Testing ABRT Crash D etection ad d in g - group, Adding a New Group - user, Adding a New User an acro n , C ro n an d An acro n - anacron configuration file, Configuring Anacron Jobs - user-defined tasks, Configuring Anacron Jobs an acro n t ab , C o n f ig u rin g An acro n Jo b s Ap ach e H T T P Server - additional resources - installable documentation, Additional Resources - installed documentation, Additional Resources - useful websites, Additional Resources - checking configuration, Editing the Configuration Files - checking status, Verifying the Service Status - directories - /etc/httpd/conf.d/ , Editing the Configuration Files - /usr/lib/httpd/modules/ , Working with Modules - /usr/lib64/httpd/modules/ , Working with Modules - files 511 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide - /etc/httpd/conf.d/nss.conf , Enabling the mod_nss Module - /etc/httpd/conf.d/ssl.conf , Enabling the mod_ssl Module - /etc/httpd/conf/httpd.conf , Editing the Configuration Files - modules - developing, Writing a Module loading, Loading a Module mod_ssl , Setting Up an SSL Server mod_userdir, Updating the Configuration - restarting, Restarting the Service - SSL server - certificate, An Overview of Certificates and Security, Using an Existing Key and Certificate, Generating a New Key and Certificate - certificate authority, An Overview of Certificates and Security - private key, An Overview of Certificates and Security, Using an Existing Key and Certificate, Generating a New Key and Certificate - public key, An Overview of Certificates and Security - starting, Starting the Service - stopping, Stopping the Service - version 2.4 - changes, Notable Changes - updating from version 2.2, Updating the Configuration - virtual host, Setting Up Virtual Hosts at , At an d B at ch - additional resources, Additional Resources Au t o mat ed T asks, Au t o mat in g Syst em T asks B b at ch , At an d B at ch - additional resources, Additional Resources b lkid , U sin g t h e b lkid C o mman d b o o t lo ad er - GRUB 2 boot loader, Working with the GRUB 2 Boot Loader - verifying, Verifying the Boot Loader b o o t med ia, Prep arin g t o U p g rad e C ch - email .f et ch mailrc - global options, Global Options C o n f ig u rat io n File C h an g es, Preservin g C o n f ig u rat io n File C h an g es C PU u sag e, Viewin g C PU U sag e creat erep o , C reat in g a Yu m R ep o sit o ry cro n , C ro n an d An acro n - additional resources, Additional Resources - cron configuration file, Configuring Cron Jobs - user-defined tasks, Configuring Cron Jobs 512 Revision Hist ory cro n t ab , C o n f ig u rin g C ro n Jo b s C U PS ( see Prin t Set t in g s) D d f , U sin g t h e d f C o mman d d irect o ry server ( see O p en LD AP) d o cu men t at io n - finding installed, Common Examples of RPM Usage d rivers ( see kern el mo d u le) d u , U sin g t h e d u C o mman d E EC D SA keys - generating, Generating Key Pairs email - additional resources, Additional Resources - installed documentation, Installed D ocumentation - related books, Related Books - useful websites, Useful Websites - Fetchmail, Fetchmail - mail server - D ovecot, D ovecot - Postfix, Postfix Procmail, Mail D elivery Agents program classifications, Email Program Classifications protocols, Email Protocols - IMAP, IMAP - POP, POP - SMTP, SMTP - security, Securing Communication - clients, Secure Email Clients - servers, Securing Email Client Communications - Sendmail, Sendmail - spam - filtering out, Spam Filters - types - Mail D elivery Agent, Mail D elivery Agent - Mail Transport Agent, Mail Transport Agent - Mail User Agent, Mail User Agent ext ra p ackag es f o r En t erp rise Lin u x ( EPEL) - installable packages, Finding RPM Packages F Fet ch mail, Fet ch mail - additional resources, Additional Resources - command options, Fetchmail Command Options 513 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide - informational, Informational or D ebugging Options - special, Special Options - configuration options, Fetchmail Configuration Options - global options, Global Options - server options, Server Options - user options, User Options f ile syst ems, Viewin g B lo ck D evices an d File Syst ems f in d mn t , U sin g t h e f in d mn t C o mman d f ree, U sin g t h e f ree C o mman d FT P, FT P - (see also vsftpd) active mode, The File Transfer Protocol command port, The File Transfer Protocol data port, The File Transfer Protocol definition of, FTP introducing, The File Transfer Protocol passive mode, The File Transfer Protocol G g n o me- syst em- lo g ( see Syst em Lo g ) g n o me- syst em- mo n it o r, U sin g t h e Syst em Mo n it o r T o o l, U sin g t h e Syst em Mo n it o r T o o l, U sin g t h e Syst em Mo n it o r T o o l, U sin g t h e Syst em Mo n it o r T o o l G n u PG - checking RPM package signatures, Checking Package Signatures g ro u p co n f ig u rat io n - groupadd, Adding a New Group - viewing list of groups, Managing Users in a Graphical Environment g ro u p s ( see g ro u p co n f ig u rat io n ) - additional resources, Additional Resources - installed documentation, Additional Resources - GID , Managing Users and Groups introducing, Managing Users and Groups shared directories, Creating Group D irectories tools for management of - groupadd, User Private Groups, Using Command Line Tools - user private, User Private Groups G RUB 2 - configuring GRUB 2, Working with the GRUB 2 Boot Loader - customizing GRUB 2, Working with the GRUB 2 Boot Loader - reinstalling GRUB 2, Working with the GRUB 2 Boot Loader H h ard ware - viewing, Viewing Hardware Information H T T P server ( see Ap ach e H T T P Server) h t t p d ( see Ap ach e H T T P Server ) 514 Revision Hist ory I in f o rmat io n - about your system, System Monitoring Tools in it ial R AM d isk imag e - verifying, Verifying the Initial RAM D isk Image - IBM eServer System i, Verifying the Initial RAM D isk Image in it ial R PM rep o sit o ries - installable packages, Finding RPM Packages in smo d , Lo ad in g a Mo d u le - (see also kernel module) in st allin g t h e kern el, Man u ally U p g rad in g t h e K ern el K kern el - downloading, D ownloading the Upgraded Kernel installing kernel packages, Manually Upgrading the Kernel kernel packages, Overview of Kernel Packages package, Manually Upgrading the Kernel performing kernel upgrade, Performing the Upgrade RPM package, Manually Upgrading the Kernel upgrade kernel available, D ownloading the Upgraded Kernel - Security Errata, D ownloading the Upgraded Kernel - via Red Hat network, D ownloading the Upgraded Kernel - upgrading - preparing, Preparing to Upgrade - working boot media, Preparing to Upgrade - upgrading the kernel, Manually Upgrading the Kernel kern el mo d u le - definition, Working with Kernel Modules - directories - /etc/modules-load.d/, Persistent Module Loading - /lib/modules/kernel_version/kernel/drivers/, Loading a Module - files - /proc/modules, Listing Currently-Loaded Modules - listing - currently loaded modules, Listing Currently-Loaded Modules - module information, D isplaying Information About a Module - loading - at the boot time, Persistent Module Loading - for the current session, Loading a Module - module parameters - supplying, Setting Module Parameters - unloading, Unloading a Module 515 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide - utilities - insmod, Loading a Module lsmod, Listing Currently-Loaded Modules modinfo, D isplaying Information About a Module modprobe, Loading a Module, Unloading a Module rmmod, Unloading a Module kern el p ackag e - kernel - for single, multicore and multiprocessor systems, Overview of Kernel Packages - kernel-devel - kernel headers and makefiles, Overview of Kernel Packages - kernel-doc - documentation files, Overview of Kernel Packages - kernel-headers - C header files files, Overview of Kernel Packages - linux-firmware - firmware files, Overview of Kernel Packages - perf - firmware files, Overview of Kernel Packages kern el u p g rad in g - preparing, Preparing to Upgrade keyb o ard co n f ig u rat io n , Syst em Lo cale an d K eyb o ard C o n f ig u rat io n - layout, Changing the Keyboard Layout L LD AP ( see O p en LD AP) lo calect l ( see keyb o ard co n f ig u rat io n ) lo g f iles, - Viewin g an d Man ag in g Lo g Files (see also System Log) description, Viewing and Managing Log Files locating, Locating Log Files monitoring, Monitoring Log Files rotating, Locating Log Files rsyslogd daemon, Viewing and Managing Log Files viewing, Viewing Log Files lo g ro t at e, Lo cat in g Lo g Files lsb lk, U sin g t h e lsb lk C o mman d lscp u , U sin g t h e lscp u C o mman d lsmo d , List in g C u rren t ly- Lo ad ed Mo d u les - (see also kernel module) lsp ci, U sin g t h e lsp ci C o mman d lsu sb , U sin g t h e lsu sb C o mman d 516 Revision Hist ory M Mail D elivery Ag en t ( see email) Mail T ran sp o rt Ag en t ( see email) ( see MT A) Mail T ran sp o rt Ag en t Swit ch er, Mail T ran sp o rt Ag en t ( MT A) C o n f ig u rat io n Mail U ser Ag en t , Mail T ran sp o rt Ag en t ( MT A) C o n f ig u rat io n ( see email) MD A ( see Mail D elivery Ag en t ) memo ry u sag e, Viewin g Memo ry U sag e mo d in f o , D isp layin g In f o rmat io n Ab o u t a Mo d u le - (see also kernel module) mo d p ro b e, Lo ad in g a Mo d u le, U n lo ad in g a Mo d u le - (see also kernel module) mo d u le ( see kern el mo d u le) mo d u le p aramet ers ( see kern el mo d u le) MT A ( see Mail T ran sp o rt Ag en t ) - setting default, Mail Transport Agent (MTA) Configuration - switching with Mail Transport Agent Switcher, Mail Transport Agent (MTA) Configuration MU A, Mail T ran sp o rt Ag en t ( MT A) C o n f ig u rat io n ( see Mail U ser Ag en t ) N n et p ro g ram, Samb a D ist rib u t io n Pro g rams n mb lo o ku p p ro g ram, Samb a D ist rib u t io n Pro g rams O o p an n o t at e ( see O Pro f ile) o p co n t ro l ( see O Pro f ile) O p en LD AP - backends, Loading Modules and Backends - checking status, Verifying the Service Status - client applications, Overview of Common LD AP Client Applications - configuration - database, Changing the D atabase-Specific Configuration - global, Changing the Global Configuration - overview, OpenLD AP Server Setup - TLS, Establishing a Secure Connection, Setting Up Replication, Loading Modules and Backends - directives - olcAllows, Changing the Global Configuration - olcConnMaxPending, Changing the Global Configuration - olcConnMaxPendingAuth, Changing the Global Configuration - olcD isallows, Changing the Global Configuration - olcIdleTimeout, Changing the Global Configuration - olcLogFile, Changing the Global Configuration - olcReadOnly, Changing the D atabase-Specific Configuration - olcReferral, Changing the Global Configuration - olcRootD N, Changing the D atabase-Specific Configuration - olcRootPW, Changing the D atabase-Specific Configuration 517 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide - olcSuffix, Changing the D atabase-Specific Configuration - olcWriteTimeout, Changing the Global Configuration - directories - /etc/openldap/slapd.d/, Configuring an OpenLD AP Server, Setting Up Replication, Loading Modules and Backends - /etc/openldap/slapd.d/cn=config/cn=schema/, Extending Schema - features, OpenLD AP Features - files - /etc/openldap/ldap.conf, Configuring an OpenLD AP Server, Establishing a Secure Connection - /etc/openldap/slapd.d/cn=config.ldif, Changing the Global Configuration, Establishing a Secure Connection - /etc/openldap/slapd.d/cn=config/olcD atabase={1}bdb.ldif, Changing the D atabase-Specific Configuration - installation, Installing the OpenLD AP Suite - migrating authentication information, Migrating Old Authentication Information to LD AP Format - modules, Loading Modules and Backends - packages, Installing the OpenLD AP Suite - replication, Setting Up Replication - restarting, Restarting the Service - running, Starting the Service - schema, Extending Schema - security, Establishing a Secure Connection - stopping, Stopping the Service - terminology - attribute, LD AP Terminology - entry, LD AP Terminology - LD IF, LD AP Terminology - utilities, Overview of OpenLD AP Server Utilities, Overview of OpenLD AP Client Utilities O p en SSH , O p en SSH , Main Feat u res - (see also SSH) - client, OpenSSH Clients - scp, Using the scp Utility - sftp, Using the sftp Utility - ssh, Using the ssh Utility - ECD SA keys - generating, Generating Key Pairs - RSA keys - generating, Generating Key Pairs - server, Starting an OpenSSH Server - starting, Starting an OpenSSH Server - stopping, Starting an OpenSSH Server - ssh-add, Configuring ssh-agent - ssh-agent, Configuring ssh-agent - ssh-keygen - ECD SA, Generating Key Pairs - RSA, Generating Key Pairs 518 Revision Hist ory - using key-based authentication, Using Key-based Authentication O p en SSL - SSL (see SSL ) - TLS (see TLS ) o p h elp , Set t in g Even t s t o Mo n it o r o p rep o rt ( see O Pro f ile) O Pro f ile, O Pro f ile - /dev/oprofile/, Understanding the /dev/oprofile/ directory - additional resources, Additional Resources - configuring, Configuring OProfile Using Legacy Mode - separating profiles, Separating Kernel and User-space Profiles - events - sampling rate, Sampling Rate - setting, Setting Events to Monitor - Java, OProfile Support for Java monitoring the kernel, Specifying the Kernel opannotate, Using opannotate opcontrol, Configuring OProfile Using Legacy Mode - --no-vmlinux, Specifying the Kernel - --start, Starting and Stopping OProfile Using Legacy Mode - --vmlinux=, Specifying the Kernel - ophelp, Setting Events to Monitor - opreport, Using opreport, Getting More D etailed Output on the Modules - on a single executable, Using opreport on a Single Executable - oprofiled, Starting and Stopping OProfile Using Legacy Mode - log file, Starting and Stopping OProfile Using Legacy Mode - overview of tools, Overview of Tools reading data, Analyzing the D ata saving data, Saving D ata in Legacy Mode starting, Starting and Stopping OProfile Using Legacy Mode SystemTap, OProfile and SystemTap unit mask, Unit Masks o p ro f iled ( see O Pro f ile) o p ro f _st art , G rap h ical In t erf ace P p ackag e - kernel RPM, Manually Upgrading the Kernel p ackag e g ro u p s - listing package groups with yum - yum groups, Listing Package Groups p ackag es, Wo rkin g wit h Packag es - dependencies, Satisfying Unresolved D ependencies - determining file ownership with, Common Examples of RPM Usage - displaying packages 519 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide - yum info, D isplaying Package Information - displaying packages with yum - yum info, D isplaying Package Information - downloading packages with yum, D ownloading Packages extra packages for Enterprise Linux (EPEL), Finding RPM Packages finding deleted files from, Common Examples of RPM Usage finding Red Hat RPM packages, Finding RPM Packages initial RPM repositories, Finding RPM Packages installing a package group with yum, Installing a Package Group installing RPM, Installing and Upgrading Packages installing with yum, Installing Packages kernel - for single, multicore and multiprocessor systems, Overview of Kernel Packages - kernel-devel - kernel headers and makefiles, Overview of Kernel Packages - kernel-doc - documentation files, Overview of Kernel Packages - kernel-headers - C header files files, Overview of Kernel Packages - linux-firmware - firmware files, Overview of Kernel Packages - listing packages with yum - Glob expressions, Searching Packages - yum list available, Listing Packages - yum list installed, Listing Packages - yum repolist, Listing Packages - yum search, Listing Packages - locating documentation for, Common Examples of RPM Usage - obtaining list of files, Common Examples of RPM Usage - perf - firmware files, Overview of Kernel Packages - 520 querying uninstalled, Common Examples of RPM Usage Red Hat Enterprise Linux installation media, Finding RPM Packages removing, Uninstalling Packages RPM, RPM - already installed, Replacing Already-Installed Packages - configuration file changes, Preserving Changes in Configuration Files - conflict, Resolving File Conflicts - failed dependencies, Satisfying Unresolved D ependencies - freshening, Freshening Packages - pristine sources, RPM D esign Goals - querying, Querying Packages - removing, Uninstalling Packages - source and binary packages, RPM - tips, Common Examples of RPM Usage - uninstalling, Uninstalling Packages - verifying, Verifying Packages Revision Hist ory - searching packages with yum - yum search, Searching Packages - uninstalling packages with yum, Removing Packages - upgrading RPM, Installing and Upgrading Packages - Yum instead of RPM, RPM p asswo rd s - shadow, Shadow Passwords p d b ed it p ro g ram, Samb a D ist rib u t io n Pro g rams Po st f ix, Po st f ix - default installation, The D efault Postfix Installation p o st f ix, Mail T ran sp o rt Ag en t ( MT A) C o n f ig u rat io n Prin t Set t in g s - CUPS, Print Settings - IPP Printers, Adding an IPP Printer - LD P/LPR Printers, Adding an LPD /LPR Host or Printer - Local Printers, Adding a Local Printer - New Printer, Starting Printer Setup - Print Jobs, Managing Print Jobs - Samba Printers, Adding a Samba (SMB) printer - Settings, The Settings Page - Sharing Printers, Sharing Printers p rin t ers ( see Prin t Set t in g s) p ro cesses, Viewin g Syst em Pro cesses Pro cmail, Mail D elivery Ag en t s - additional resources, Additional Resources - configuration, Procmail Configuration - recipes, Procmail Recipes - delivering, D elivering vs. Non-D elivering Recipes - examples, Recipe Examples - flags, Flags - local lockfiles, Specifying a Local Lockfile - non-delivering, D elivering vs. Non-D elivering Recipes - SpamAssassin, Spam Filters - special actions, Special Conditions and Actions - special conditions, Special Conditions and Actions p s, U sin g t h e p s C o mman d R R AM, Viewin g Memo ry U sag e rcp , U sin g t h e scp U t ilit y R ed H at Su p p o rt T o o l - getting support on the command line, Accessing Support Using the Red Hat Support Tool R ed H at En t erp rise Lin u x in st allat io n med ia - installable packages, Finding RPM Packages 521 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide R ed H at Su b scrip t io n Man ag emen t - subscription, Registering the System and Attaching Subscriptions rmmo d , U n lo ad in g a Mo d u le - (see also kernel module) rp cclien t p ro g ram, Samb a D ist rib u t io n Pro g rams R PM, R PM - additional resources, Additional Resources - already installed, Replacing Already-Installed Packages - basic modes, Using RPM - checking package signatures, Checking Package Signatures - configuration file changes, Preserving Changes in Configuration Files - conf.rpmsave, Preserving Changes in Configuration Files - conflicts, Resolving File Conflicts - dependencies, Satisfying Unresolved D ependencies - design goals, RPM D esign Goals - powerful querying, RPM D esign Goals - system verification, RPM D esign Goals - upgradability, RPM D esign Goals - determining file ownership with, Common Examples of RPM Usage documentation with, Common Examples of RPM Usage failed dependencies, Satisfying Unresolved D ependencies file conflicts - resolving, Resolving File Conflicts - file name, Installing and Upgrading Packages finding and verifying RPM packages, Finding and Verifying RPM Packages finding deleted files with, Common Examples of RPM Usage finding Red Hat RPM packages, Finding RPM Packages freshening, Freshening Packages GnuPG, Checking Package Signatures installing, Installing and Upgrading Packages online documentation, Additional Resources querying, Querying Packages querying for file list, Common Examples of RPM Usage querying uninstalled packages, Common Examples of RPM Usage see also, Additional Resources tips, Common Examples of RPM Usage uninstalling, Uninstalling Packages upgrading, Installing and Upgrading Packages verification, Verifying Packages verifying, Verifying Packages website, Additional Resources R PM Packag e Man ag er ( see R PM) R SA keys - generating, Generating Key Pairs rsyslo g , Viewin g an d Man ag in g Lo g Files - actions, Actions - configuration, Basic Configuration of Rsyslog - debugging, D ebugging Rsyslog 522 Revision Hist ory - filters, Filters global directives, Global D irectives log rotation, Log Rotation modules, Using Rsyslog Modules new configuration format, Using the New Configuration Format queues, Working with Queues in Rsyslog rulesets, Rulesets templates, Templates S Samb a ( see Samb a) - Abilities, Samba Features - Additional Resources, Additional Resources - installed documentation, Installed D ocumentation - useful websites, Useful Websites - Browsing, Samba Network Browsing - configuration, Configuring a Samba Server, Command Line Configuration - default, Configuring a Samba Server - daemon, Samba D aemons and Related Services - nmbd, Samba D aemons - overview, Samba D aemons - smbd, Samba D aemons - winbindd, Samba D aemons - encrypted passwords, Encrypted Passwords graphical configuration, Graphical Configuration Introduction, Introduction to Samba Network Browsing, Samba Network Browsing - D omain Browsing, D omain Browsing - WINS, WINS (Windows Internet Name Server) - Programs, Samba D istribution Programs - net, Samba D istribution Programs - nmblookup, Samba D istribution Programs - pdbedit, Samba D istribution Programs - rpcclient, Samba D istribution Programs - smbcacls, Samba D istribution Programs - smbclient, Samba D istribution Programs - smbcontrol, Samba D istribution Programs - smbpasswd, Samba D istribution Programs - smbspool, Samba D istribution Programs - smbstatus, Samba D istribution Programs - smbtar, Samba D istribution Programs - testparm, Samba D istribution Programs - wbinfo, Samba D istribution Programs - Reference, Samba - Samba Printers, Adding a Samba (SMB) printer - service - conditional restarting, Starting and Stopping Samba - reloading, Starting and Stopping Samba - restarting, Starting and Stopping Samba - starting, Starting and Stopping Samba - stopping, Starting and Stopping Samba 523 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide - share - connecting to via the command line, Command Line - connecting to with Nautilus, Connecting to a Samba Share - mounting, Mounting the Share - smbclient, Command Line - WINS, WINS (Windows Internet Name Server) - with Windows NT 4.0, 2000, ME, and XP, Encrypted Passwords scp ( see O p en SSH ) secu rit y p lu g - in ( see Secu rit y) Secu rit y- R elat ed Packag es - updating security-related packages, Updating Packages Sen d mail, Sen d mail - additional resources, Additional Resources - aliases, Masquerading - common configuration changes, Common Sendmail Configuration Changes - default installation, The D efault Sendmail Installation - LD AP and, Using Sendmail with LD AP - limitations, Purpose and Limitations - masquerading, Masquerading - purpose, Purpose and Limitations - spam, Stopping Spam - with UUCP, Common Sendmail Configuration Changes sen d mail, Mail T ran sp o rt Ag en t ( MT A) C o n f ig u rat io n sf t p ( see O p en SSH ) sh ad o w p asswo rd s - overview of, Shadow Passwords slap d ( see O p en LD AP) smb cacls p ro g ram, Samb a D ist rib u t io n Pro g rams smb clien t , C o mman d Lin e smb clien t p ro g ram, Samb a D ist rib u t io n Pro g rams smb co n t ro l p ro g ram, Samb a D ist rib u t io n Pro g rams smb p asswd p ro g ram, Samb a D ist rib u t io n Pro g rams smb sp o o l p ro g ram, Samb a D ist rib u t io n Pro g rams smb st at u s p ro g ram, Samb a D ist rib u t io n Pro g rams smb t ar p ro g ram, Samb a D ist rib u t io n Pro g rams Sp amAssassin - using with Procmail, Spam Filters ssh ( see O p en SSH ) SSH p ro t o co l - authentication, Authentication - configuration files, Configuration Files - system-wide configuration files, Configuration Files - user-specific configuration files, Configuration Files - connection sequence, Event Sequence of an SSH Connection 524 Revision Hist ory - features, Main Features - insecure protocols, Requiring SSH for Remote Connections - layers - channels, Channels - transport layer, Transport Layer - port forwarding, Port Forwarding requiring for remote login, Requiring SSH for Remote Connections security risks, Why Use SSH? version 1, Protocol Versions version 2, Protocol Versions X11 forwarding, X11 Forwarding ssh - ad d , C o n f ig u rin g ssh - ag en t ssh - ag en t , C o n f ig u rin g ssh - ag en t SSL , Set t in g U p an SSL Server - (see also Apache HTTP Server ) SSL server ( see Ap ach e H T T P Server ) st u n n el, Secu rin g Email C lien t C o mmu n icat io n s su b scrip t io n s, R eg ist erin g t h e Syst em an d Man ag in g Su b scrip t io n s syst em an alysis - OProfile (see OProfile) syst em in f o rmat io n - cpu usage, Viewing CPU Usage - file systems, Viewing Block D evices and File Systems - gathering, System Monitoring Tools - hardware, Viewing Hardware Information - memory usage, Viewing Memory Usage - processes, Viewing System Processes - currently running, Using the top Command Syst em Lo g - filtering, Viewing Log Files - monitoring, Monitoring Log Files - refresh rate, Viewing Log Files - searching, Viewing Log Files Syst em Mo n it o r, U sin g t h e Syst em Mo n it o r T o o l, U sin g t h e Syst em Mo n it o r T o o l, U sin g t h e Syst em Mo n it o r T o o l, U sin g t h e Syst em Mo n it o r T o o l syst ems - registration, Registering the System and Managing Subscriptions - subscription management, Registering the System and Managing Subscriptions T t est p arm p ro g ram, Samb a D ist rib u t io n Pro g rams t h e U sers set t in g s t o o l ( see u ser co n f ig u rat io n ) T LS , Set t in g U p an SSL Server - (see also Apache HTTP Server ) t o p , U sin g t h e t o p C o mman d 525 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide U u ser co n f ig u rat io n - command line configuration - passwd, Adding a New User - useradd, Adding a New User - viewing list of users, Managing Users in a Graphical Environment u ser p rivat e g ro u p s ( see g ro u p s) - and shared directories, Creating Group D irectories u serad d co mman d - user account creation using, Adding a New User u sers ( see u ser co n f ig u rat io n ) - additional resources, Additional Resources - installed documentation, Additional Resources - introducing, Managing Users and Groups - tools for management of - the Users setting tool, Using Command Line Tools - useradd, Using Command Line Tools - UID , Managing Users and Groups V virt u al h o st ( see Ap ach e H T T P Server ) vsf t p d - additional resources, Additional Resources - installed documentation, Installed D ocumentation - online documentation, Online D ocumentation - encrypting, Encrypting vsftpd Connections Using TLS multihome configuration, Starting Multiple Copies of vsftpd restarting, Starting and Stopping vsftpd securing, Encrypting vsftpd Connections Using TLS, SELinux Policy for vsftpd SELinux, SELinux Policy for vsftpd starting, Starting and Stopping vsftpd starting multiple copies of, Starting Multiple Copies of vsftpd status, Starting and Stopping vsftpd stopping, Starting and Stopping vsftpd TLS, Encrypting vsftpd Connections Using TLS W wb in f o p ro g ram, Samb a D ist rib u t io n Pro g rams web server ( see Ap ach e H T T P Server) Win d o ws 2000 - connecting to shares using Samba, Encrypted Passwords Win d o ws 9 8 - connecting to shares using Samba, Encrypted Passwords Win d o ws ME - connecting to shares using Samba, Encrypted Passwords 526 Revision Hist ory Win d o ws N T 4 .0 - connecting to shares using Samba, Encrypted Passwords Win d o ws XP - connecting to shares using Samba, Encrypted Passwords X X.500 ( see O p en LD AP) X.500 Lit e ( see O p en LD AP) Y Yu m - configuring plug-ins, Enabling, Configuring, and D isabling Yum Plug-ins configuring yum and yum repositories, Configuring Yum and Yum Repositories disabling plug-ins, Enabling, Configuring, and D isabling Yum Plug-ins displaying packages - yum info, D isplaying Package Information - displaying packages with yum - yum info, D isplaying Package Information - downloading packages with yum, D ownloading Packages enabling plug-ins, Enabling, Configuring, and D isabling Yum Plug-ins installing a package group with yum, Installing a Package Group installing with yum, Installing Packages listing package groups with yum - yum groups list, Listing Package Groups - listing packages with yum - Glob expressions, Searching Packages - yum list, Listing Packages - yum list available, Listing Packages - yum list installed, Listing Packages - yum repolist, Listing Packages - packages, Working with Packages - plug-ins - aliases, Working with Yum Plug-ins - kabi, Working with Yum Plug-ins - langpacks, Working with Yum Plug-ins - product-id, Working with Yum Plug-ins - yum-changelog, Working with Yum Plug-ins - yum-tmprepo, Working with Yum Plug-ins - yum-verify, Working with Yum Plug-ins - yum-versionlock, Working with Yum Plug-ins - repository, Adding, Enabling, and D isabling a Yum Repository, Creating a Yum Repository - searching packages with yum - yum search, Searching Packages - setting [main] options, Setting [main] Options setting [repository] options, Setting [repository] Options uninstalling packages with yum, Removing Packages variables, Using Yum Variables Yum plug-ins, Yum Plug-ins 527 Red Hat Ent erprise Linux 7 Syst em Administ rat or's G uide - Yum repositories - configuring yum and yum repositories, Configuring Yum and Yum Repositories Yu m U p d at es - checking - updating - updating - updating - updating 528 for updates, Checking For Updates a single package, Updating Packages all packages and dependencies, Updating Packages packages, Updating Packages security-related packages, Updating Packages
Source Exif Data:
File Type : PDF File Type Extension : pdf MIME Type : application/pdf PDF Version : 1.4 Linearized : No Title : Red Hat Enterprise Linux 7 System Administrator's Guide Creator : wkhtmltopdf 0.12.1-development Producer : Qt 4.8.6 Create Date : 2015:04:03 10:16:54-04:00 Page Count : 533 Page Mode : UseOutlinesEXIF Metadata provided by EXIF.tools