bS]@sdZddlZddlZddlZddlmZddlZddlmZm Z m Z ddl m Z ddl ZddZdd ZGd d d ZdS) z'frontend.py: frontend interface for ufwN)UFWError)errorwarnmsg)UFWBackendIptablescCstjj}x?ddddddddgD]}|jtjj|q.Wx3d d d d gD]}|jtjj|qdWx9d dddddgD]}|jtjj|qWx0dddgD]}|jtjj|qWx0dddgD]}|jtjj|qWx?dddddddd gD]}|jtjj |qHWdd!ddd"d#g}x@|D]8}|jtjj ||jtjj |qWt |d$krUd%}||j d&krd$}n||j d krU||j d'krU||j |krU|j|d(qUnt |d$ksd&|krt |d)krtd*ny|j|d%d}WnZtk r}ztd+|jWYdd}~Xn%tk r td,d-d.YnX|S)/zEParse command. Returns tuple for action, rule, ip_version and dryrun.enabledisablehelpz--helpversionz --versionreloadresetlistinfodefaultupdateonoffZlowZmediumZhighfullallowdenyrejectNverboseZnumberedrawz before-rulesz user-rulesz after-rulesz logging-rulesbuiltins listeningaddedlimitinsertdeletez --dry-runZrouteruleznot enough argsz%szInvalid syntaxZdo_exitF)ufwparserZ UFWParserZregister_commandZUFWCommandBasicZ UFWCommandAppZUFWCommandLoggingZUFWCommandDefaultZUFWCommandStatusZUFWCommandShowUFWCommandRuleUFWCommandRouteRulelenlowerrr parse_commandrvalue Exception)argvpiZ rule_commandsidxprer2./usr/lib/python3/dist-packages/ufw/frontend.pyr)sJ  0 # r)cCstditjjd6dd6dd6dd6dd6d d 6d d 6d d6dd6dd6dd6dd6dd6dd6dd6dd6dd6d d 6d!d!6d"d"6d#d$6d%d&6d'd(6d)d*6d+d+6d,d-6d.d/6d0d16d2d36d4d56d6d76}|S)8zPrint help messagea Usage: %(progname)s %(command)s %(commands)s: %(enable)-31s enables the firewall %(disable)-31s disables the firewall %(default)-31s set default policy %(logging)-31s set logging to %(level)s %(allow)-31s add allow %(rule)s %(deny)-31s add deny %(rule)s %(reject)-31s add reject %(rule)s %(limit)-31s add limit %(rule)s %(delete)-31s delete %(urule)s %(insert)-31s insert %(urule)s at %(number)s %(reload)-31s reload firewall %(reset)-31s reset firewall %(status)-31s show firewall status %(statusnum)-31s show firewall status as numbered list of %(rules)s %(statusverbose)-31s show verbose firewall status %(show)-31s show firewall report %(version)-31s display version information %(appcommands)s: %(applist)-31s list application profiles %(appinfo)-31s show information on %(profile)s %(appupdate)-31s update %(profile)s %(appdefault)-31s set default application policy ZprognameZCOMMANDZcommandZCommandsZcommandsrrz default ARGrz logging LEVELZloggingZLEVELlevelz allow ARGSrr!z deny ARGSrz reject ARGSrz limit ARGSrzdelete RULE|NUMrZRULEZurulezinsert NUM RULErZNUMnumberr r statuszstatus numberedZ statusnumZRULESruleszstatus verboseZ statusverbosezshow ARGshowr zApplication profile commandsZ appcommandszapp listZapplistzapp info PROFILEZappinfoZPROFILEprofilezapp update PROFILEZ appupdatezapp default ARGZ appdefault)_r#commonZ programName)Zhelp_msgr2r2r3get_command_helpXsBr<c@seZdZdZdddZddZddZd d Zd d d d ZdddZ ddZ ddZ ddZ d ddZ d ddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd d)d*Zd+S), UFWFrontendZUIiptablesc Cs{|dkr:yt||_WqJtk r6YqJXntd|td|_td|_td|_dS)Nr>zUnsupported backend type '%s'nyyes)rbackendr+rr:norAyes_full)selfdryrunZ backend_typer2r2r3__init__s   zUFWFrontend.__init__c,Csd}d}|rd}nd}|r7|jj sM| rV|jjrVd}n|ry$|jj|jjdd|Wqtk r}zt|jWYdd}~XqXnd}|ry|jjWn7tk r}z|r|j}nWYdd}~XnX|dkry$|jj|jjdddWn2tk rs}zt|jWYdd}~XnXt|ntd }nRy|jj Wn2tk r}zt|jWYdd}~XnXtd }|S) zlToggles ENABLED state in /ufw/ufw.conf and starts or stops running firewall. rCrAFTconfZENABLEDNz0Firewall is active and enabled on system startupz/Firewall stopped and disabled on system startup) rB is_enabledZ set_defaultfilesrrr*start_firewallr: stop_firewall)rEenabledresZ config_strZchangedr1Z error_strr2r2r3 set_enabledsF  #     zUFWFrontend.set_enabledcCsd}yE|jj||}|jjrJ|jj|jjnWn2tk r}zt|jWYdd}~XnX|S)zSets default policy of firewallrHN)rBset_default_policyrJrMrLrrr*)rEpolicy directionrOr1r2r2r3rQs  zUFWFrontend.set_default_policycCsUd}y|jj|}Wn2tk rP}zt|jWYdd}~XnX|S)zSets log level of firewallrHN)rB set_loglevelrrr*)rEr4rOr1r2r2r3rTs  zUFWFrontend.set_loglevelFcCsRy|jj||}Wn2tk rM}zt|jWYdd}~XnX|S)zShows status of firewallN)rB get_statusrrr*)rErZ show_countoutr1r2r2r3rUs  zUFWFrontend.get_statusrcCsOy|jj|}Wn2tk rJ}zt|jWYdd}~XnX|S)zShows raw output of firewallN)rBZget_running_rawrrr*)rEZ rules_typerVr1r2r2r3 get_show_raws  zUFWFrontend.get_show_rawcCsd}ytjj|jj}Wn*tk rQtd}t|YnX|jj}t |j }|j xR|D]J}|jj r|d"krqn|d|7}t ||j }|j x|D]}x|||D]} | d} | j d r| j d rd} |d |7}| d ksR| d krm|d 7}d | d} n |d| 7}tjj | } |dtjj| d7}tjjddd|ddd|d| dddd} | j|jd| dkr| jd| n| j|jj| } t| dkr|d7}xa| D]V}|dkr\|dt|kr\|d |tjjj||df7}q\q\Wn|d7}qqWqWqW|jjstjjd!n|S)#zMShows listening services and incoming rules that might affect themrHzCould not get listening statustcp6udp6z%s: Zladdrz127.z::1z %s z0.0.0.0z::z* z%s/0z%s z(%s)exeactionrZprotocolNr"ZdportdstrSinforwardF6r r z [%2d] %s z)Skipping tcp6 and udp6 (IPv6 is disabled))rXrY)r#utilZparse_netstat_outputrBuse_ipv6r+r:r get_rulesr keyssort startswithZget_if_from_ipospathbasenamer;ZUFWRuleset_v6endswithZ set_interfaceZ normalizeZ get_matchingr'r$r% get_commanddebug)rErOderr_msgr7Z protocolsprotoportsZportitemZaddrZifnamer!Zmatchingr.r2r2r3get_show_listeningsd             "   zUFWFrontend.get_show_listeningcCs|jj}td}t|dkr;|tdSg}x~|jjD]m}|jr|dtjjj|}ntjj j|}||krqQn|j ||d|7}qQW|S)z!Shows added rules to the firewallz9Added user rules (see 'ufw status' for running firewall):rz (None)zroute %sz ufw %s) rBrcr:r'r^r#r$r&rlr%append)rEr7rVrrrstrr2r2r3get_show_addedOs    zUFWFrontend.get_show_addedcCsd}d}d}g}|jdkrF|jdkrF|j|n)g}y |jr(|dkr||jj|d}n|dkr|jj|d}n|dkr5|jj|d}|jj|d}xx|D]Q} xH|D]@} | j} d| _| j| s| | _|j| qqWqWntd|}t |t |dkr|jj rtd }|dkr|}n:|dkr|d }n!|dkr|d |d }n|Sx|D]K}|j } |j| _| j |j| j|j|j| qWn.|jj|}|jdkrV|jnWntk rnYnXd} d}td }|jjd}|jjd}xt|D]\}} |} | j||kr|t| jd 7}t |nyX|jjr|dkrx| j|krV|t| jd 7}t |n| jd|jj| }qZ|dkr| j|kr| j| j|nD| jdkr| j|kr|t| jd 7}t |n| jd|jj| }qZ|dkr| j}| jd| j r||kr|jj||| d}|dkr| j|q| jdn|jj| }| j r|dkr|jjd}| j|dn| jd| j r\| jdkr\| j|kr\|jj| jd}|dkrL| j|| q\| jdn|dkru|d 7}n| j r| j|kr| j| j|n||jj| 7}qZtd|}t |n}|dks|dkr| jd|jj| }nC|dkr>td}t |ntd|}t |Wn5t k r}z|j}d}PWYdd}~XnX| jrtd}tj |qqW|s||7}nt |dkrt!|nd}t"t#| d}|jx|D]}| dkr||r||j }d|_y|j||Wqtk rd}td| j$}t |YqXqqW|td7}|r|td7}n|td7}t ||S)zUpdates firewall with rulerHv4Fv6TZbothzInvalid IP version '%s'rz"Could not delete non-existent rulez (v6)r`zInvalid position ''r zIPv6 support not enabledNz Rule changed after normalizationzCould not back out rule '%s'z" Error applying application rules.z# Some rules could not be unapplied.z( Attempted rules successfully unapplied.)%dappsapprtremoverBZget_app_rules_from_systemrymatchr:rr'rFZdup_ruleZ set_actionr[Z set_logtypeZlogtypeZget_app_rules_from_templateZpositionreverser+Zget_rules_count enumeratestrrbrjset_ruleZ set_positionZfind_other_positionr*updatedwarningsrrr rangeZ format_rule)rEr! ip_versionrOrotmpr7ZtmprulesZ tmprules6xr@Zprev6rucountZ set_errorZ pos_err_msgZnum_v4Znum_v6r.Zuser_posr-r1Zwarn_msgZ undo_errorZindexesjZ backout_ruler2r2r3rls                                                        zUFWFrontend.set_rulec Csyt|}Wn.tk r@td|}t|YnX|jj}|dksn|t|krtd|}t|n|jj|}|std|}t|nd|_d}|j rd}nd}|s|j rdt j j j|} nt j jj|} tdi| d 6|jd 6|jd 6} t| d tjd dtjjjj} | dkr| |jkr| |jkrd}qnd} |r|j||} n td} | S)z Delete rulezCould not find rule '%s'rzCould not find rule '%d'Trxryzroute %sz=Deleting: %(rule)s Proceed with operation (%(yes)s|%(no)s)? r!rArCoutputnewlineFr@rHAborted)intr+r:rrBrcr'Zget_rule_by_numberr}ryr^r#r$r&rlr%rArCrsysstdoutstdinreadliner(striprDr) rEr5forcer?ror7r!rproceedrvpromptansrOr2r2r3 delete_rule(sH        *  zUFWFrontend.delete_rulec Csyd}|jdr^|jd}t|dkrL|j|d}qu|jd}n|dkr||jd}n|jdrtd }|jd }t|d krt|n|j|d|d }n|d kr|j|}ns|dkr|j}nX|dkr;|jd}n:|jdr|jd d}|dkrx|j }qu|dkr|j }qu|j |}n|dkr|jdd}n|dkr|j d}n|dkr|j d}ns|dkrU|j jrF|j d|j dtd}qutd}n |jdr|j|jd d|}n|dks|dks|dks|dkrY|jdkr}yD|j j|j}||jkr||_|j|d nWq}tk ry}zN|js7t|jntjj|jsgtd!}t|nWYd"d"}~Xq}Xn|jdkrDyD|j j|j}||jkr||_|j|d nWqDtk r@}zN|jst|jntjj|js.td!}t|nWYd"d"}~XqDXn|j||}ntd#|}t||S)$zPerform action on rule. action, rule and ip_version are usually based on return values from parse_command(). rHz logging-onr:r rz logging-offrzdefault-zUnsupported default policy-r"rr r6zstatus-verboseTr8rrzstatus-numberedFrrr zFirewall reloadedz&Firewall not enabled (skipping reload)zdelete-rrrrr\zInvalid profile nameNzUnsupported action '%s')rfsplitr'rTr:rrQr rUrsrwrWrPrBrJrr{Zfind_application_nameZset_portr}rr*r# applicationsvalid_profile_namer|r) rEr[r!rrrOrror1r2r2r3 do_actionXs             "$    %   % zUFWFrontend.do_actioncCsUd}y|jj|}Wn2tk rP}zt|jWYdd}~XnX|S)z+Sets default application policy of firewallrHN)rBset_default_application_policyrrr*)rErRrOr1r2r2r3rs  z*UFWFrontend.set_default_application_policycCsQt|jjj}|jtd}x|D]}|d|7}q5W|S)z*Display list of known application profileszAvailable applications:z %s)r rBprofilesrdrer:)rEnamesrvr?r2r2r3get_application_lists    z UFWFrontend.get_application_listcCs#g}|dkr7t|jjj}|jn:tjj|sdtd}t |n|j |d}x|D]}||jjks|jj| rtd|}t |ntjj ||jj|std}t |n|td|7}|tdtjj |jj|7}|tdtjj |jj|7}tjj|jj|}t|d ksd |d kr|td 7}n|td 7}x|D]}|d|7}qW||t|d kr~|d7}q~q~Wtjj|S)zDisplay information on profileallzInvalid profile namerHzCould not find profile '%s'zInvalid profilez Profile: %s z Title: %s zDescription: %s r ,rzPorts:zPort:z %sz -- )r rBrrdrer#rrr:rrtZverify_profileZ get_titleZget_descriptionZ get_portsr'ra wrap_text)rEZpnamerrorvnamerqr-r2r2r3get_application_infosB         " z UFWFrontend.get_application_infoc Csd}d}d}y(|jjr9tjjr9d}nWntk rTd}YnX|dkrt|jjj}|j x|D]P}|jj |\}}|r|dkr|d7}n||7}|}qqWn1|jj |\}}|dkr|d7}n|r||jj r||riy|jj Wntk rUYnX|t d7}q||t d7}n|S)zRefresh application profilerHTFrr`zFirewall reloadedzSkipped reloading firewall)rB do_checksr#ra under_sshr+r rrdreZupdate_app_rulerJZ_reload_user_rulesr:) rEr9rvZ allow_reloadZtrigger_reloadrr-rfoundr2r2r3application_updates<            zUFWFrontend.application_updatec Csyd}d}|dkr3td}t|n|jjd}|dkrmtjjd||f|S|dkrd}nF|d krd }n1|d krd }ntd |}t|d g}|jjr|jdn|||g7}yt |}Wnt k r$YnXd|j kr]|j |j |j d|j d}n|j |j dd}|S)zRefresh application profilerHrz%Cannot specify 'all' with '--add-new'Zdefault_application_policyskipz'Policy is '%s', not adding profile '%s'ZacceptrZdroprrzUnknown policy '%s'r#z --dry-runr!Ziptype)r:rrBZdefaultsr#rarmrFrtr)r+datarr[)rEr9rvrRrorargsr0r2r2r3application_adds>              zUFWFrontend.application_addcCsTd}|dkr$|jd}n,|dkrB|jd}n|dkr`|jd}n|dkr~|jd }n|d kr|j}n|d kr|j|}n|d ks|d kr4|j|}d}|d kr|j|}n|dkr'|dkr'|d7}n||}ntd|}t||S)zzPerform action on profile. action and profile are usually based on return values from parse_command(). rHz default-allowrz default-denyrzdefault-rejectrz default-skiprr rrzupdate-with-newr`zUnsupported action '%s')rrrrrr:r)rEr[r9rOZstr1Zstr2ror2r2r3do_application_actionDs0          z!UFWFrontend.do_application_actioncCsd}|jjrtjjrtdi|jd6|jd6}t|dt j ddt j j j j}|dkr||jkr||jkrd}qn|S) z6If running under ssh, prompt the user for confirmationTzWCommand may disrupt existing ssh connections. Proceed with operation (%(yes)s|%(no)s)? rArCrrFr@)rBrr#rarr:rArCrrrrrr(rrD)rErrrr2r2r3continue_under_sshds * zUFWFrontend.continue_under_sshcCs4d}tdi|jd6|jd6}|jjrltjjrltdi|jd6|jd6}n|jjr| rttjj |dt j ddt j j jj}|d kr||jkr||jkrtd }|Sn|jjr!||jd7}n|jj}|S) zReset the firewallrHzTResetting all rules to installed defaults. Proceed with operation (%(yes)s|%(no)s)? rArCzResetting all rules to installed defaults. This may disrupt existing ssh connections. Proceed with operation (%(yes)s|%(no)s)? rrFr@r)r:rArCrBrr#rarrrrrrrr(rrDrJrPr )rErrOrrr2r2r3r rs   %* zUFWFrontend.resetN)__name__ __module__ __qualname____doc__rGrPrQrTrUrWrsrwrrrrrrrrrrr r2r2r2r3r=s(  6   H  0V . + * r=)rrgrrZ ufw.commonrZufw.utilr#rrrZufw.backend_iptablesrZ ufw.parserr)r<r=r2r2r2r3s      < @