M/eJdUdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl m Z ddl mZddl mZddl mZddl mZdd l mZdd l mZdd l mZdd l mZddlZdd lmZddlmZddlmZddlmZddlmZe j j?dZ e rddl!Z!ejDe#Z$GddeZ%GddeZ&GddZ'dZ(dZ)dZ*ejVjYdZ-ej\Z/iZ0ee1ejdfe3d<ejhdejjZ6dee1e1ffd Z7e$jpfd!ee1d"e e1gdfdee1e1ffd#Z9d$e1de:fd%Z;d&e1ddfd'Zd+e:ddfd,Z?d^d)e1d*e>d+e:ddfd-Z@d_d.e1d*e1d/ee>defd0ZAd.e1d1e e>ge1fd2e>d/e>d*e1deee1ff d3ZBd`d.e1d/e>d*e1deee1ffd4ZC dad.e1d5e1d/e>d*e1deee1ff d6ZDd.e1ddfd7ZEd8ee1dee1fd9ZFdee1e1ffd:ZGde1fd;ZHdee1fd<ZIdbd=e1d>e1de1fd?ZJd@e1de1fdAZKdcdBe:dee1e1ffdCZLejhdDZMdEe1de:fdFZNGdGdHejZPdIe dJdKe1dLee1e>fddfdMZQdNe1de1fdOZRdNee1eSfde1fdPZTdQe1de:fdRZUdNee1eSfde:fdSZVdTe1de:fdUZWdVe dWe dXe ddfdYZXdZe1deee>e1ffd[ZYdVe dWe dXe ddfd\ZZy)dzUtilities for all Certbot.N)Any)Callable)Dict)IO)List) NamedTuple)Optional)Set)Tuple)Union)errors) constants)lock) filesystem)oslinuxc,eZdZUdZeeed<eed<y)KeyzPContainer for an optional file path and contents for a PEM-formated private key.filepemN__name__ __module__ __qualname____doc__r str__annotations__bytes./usr/lib/python3/dist-packages/certbot/util.pyrr&sZ 3- Jr rc6eZdZUdZeeed<eed<eed<y)CSRzPContainer for an optional file path and contents for a PEM or DER-formatted CSR.rdataformNrrr r!r#r#,sZ 3- K Ir r#c0eZdZdZdeddfdZdddefdZy) LooseVersionaA version with loose rules, i.e. any given string is a valid version number. but regular comparison is not supported. Instead, the `try_risky_comparison` method is provided, which may return an error if two LooseVersions are 'incomparible'. For example when integer and string version components are present in the same position. Differences with old distutils.version.LooseVersion: (https://github.com/python/cpython/blob/v3.10.0/Lib/distutils/version.py#L269) Most version comparisons should give the same result. However, if a version has multiple trailing zeroes, not all of them are used in the comparison. This ensure that, for example, "2.0" and "2.0.0" are equal. version_stringreturnNctj|Dcgc] }|r|dk7r| }}t|D]\}} t|||<||_ycc}w#t$rY/wxYw)zhParses a version string into its components. :param str version_string: version string .N)_VERSION_COMPONENT_REsplit enumerateint ValueErrorversion_components)selfr(x componentsiobjs r!__init__zLooseVersion.__init__Bs "7! other, 1 is returned. If self < other -1 is returned. Examples: Equality: - LooseVersion('1.0').try_risky_comparison(LooseVersion('1.0')) -> 0 - LooseVersion('2.0.0a').try_risky_comparison(LooseVersion('2.0.0a')) -> 0 Inequality: - LooseVersion('2.0.0').try_risky_comparison(LooseVersion('1.0')) -> 1 - LooseVersion('1.0.1').try_risky_comparison(LooseVersion('2.0a')) -> -1 Incomparability: - LooseVersion('1a').try_risky_comparison(LooseVersion('1.0')) -> ValueError r) fillvaluez~Cannot meaningfully compare LooseVersion {} with LooseVersion {} due to comparison of version components with different types.) itertools zip_longestr1 TypeErrorr0format)r2r8self_vcother_vcs r!try_risky_comparisonz!LooseVersion.try_risky_comparisonRs6 Y%.%:%:4;R;R;@;S;SEF&H !X%x'  Y]$fT%<%V>VWY Y Ys8AAAA9A>)rrrrrr7r/rCrr r!r'r'4s0 -s-t- (Y.(YS(Yr r'zzz)z$The following error was encountered:z{0}zWEither run as root, or set --config-dir, --work-dir, and --logs-dir to writeable paths._LOCKSz(\d+ | [a-z]+ | \.)r)ctjjdvsdvrSdD]6}|vsdjfd|j dD|<8S)a When Certbot is run inside a Snap, certain environment variables are modified. But Certbot sometimes calls out to external programs, since it uses classic confinement. When we do that, we must modify the env to remove our modifications so it will use the system's libraries, since they may be incompatible with the versions of libraries included in the Snap. For example, apachectl, Nginx, and anything run from inside a hook should call this function and pass the results into the ``env`` argument of ``subprocess.Popen``. :returns: A modified copy of os.environ ready to pass to Popen :rtype: dict SNAPCERTBOT_SNAPPED)PATHLD_LIBRARY_PATH:c32K|]}d|vs |yw)rFNr).0r3envs r! z1env_no_snap_for_external_calls..s%cAcRXkabNba%cs )renvironcopyjoinr-) path_namerMs @r!env_no_snap_for_external_callsrSsq **// C S-S8 0d   XX%cY1E1Ec1J%ccC Nd Jr paramslogc  tj|dtjtjdt}|jdk7rKddj |d|jd |j}||tj||j|jfS#tt f$r2ddj |z}||tj|wxYw) zRun the script with the given params. :param list params: List of parameters to pass to subprocess.run :param callable log: Logger method to use for errors FT)checkstdoutstderruniversal_newlinesrMzUnable to run the command: %s rzError while running z.  ) subprocessrunPIPErSOSErrorr0rQr SubprocessError returncoderXrY)rTrUprocmsgs r! run_scriptres *~~f$)%/__%/__15"@"B D ! HHV dkk4;;8 C$$S)) ;; ## Z *-0@@ C$$S))*s ?B33AC4execJtjj|\}}|rtj|Stj djtj D]7}tjtjj||s7yy)zDetermine whether path/name refers to an executable. :param str exe: Executable path or name :returns: If exe is a valid executable :rtype: bool rHTF)rpathr-r is_executablerOpathseprQ)rfrh_s r! exe_existsrlszggmmC GD! '',, 6"((4  # #BGGLLs$; < r dir_pathcxtstt|tvrtj|t|<yy)zLock the directory at dir_path until program exit. :param str dir_path: path to directory :raises errors.LockError: if the lock is held by another process N)rDatexit_register_release_locksrlock_dir)rms r!lock_dir_until_exitrrs/ 'v==2xr ctjD]} |jtj y#dj|}tj |dYWxYw)Nz(Exception occurred releasing lock: {0!r}Texc_info)rDvaluesreleaser@loggerdebugclear)dir_lockrds r!rprpsZMMO- -    -  LLN -<CCHMC LLtL ,s A*A, directorymodestrictc t|||t|y#t$rD}tj ddt j tj|d}~wwxYw)ahEnsure directory exists with proper permissions and is locked. :param str directory: Path to a directory. :param int mode: Directory mode. :param bool strict: require directory to be owned by current user :raises .errors.LockError: if the directory cannot be locked :raises .errors.Error: if the directory cannot be made or verified zException was:TrtN) make_or_verify_dirrrr`rxryr Error PERM_ERR_FMTr@)r|r}r~errors r!set_up_core_dirrsV79dF3I& 7 % 5ll<..u5667s A(?A##A(c tj||y#t$rh}|jtjk(r;|r?tj ||s$t j|dt|Yd}~yYd}~yd}~wwxYw)aMake sure directory exists with proper permissions. :param str directory: Path to a directory. :param int mode: Directory mode. :param bool strict: require directory to be owned by current user :raises .errors.Error: if a directory already exists, but has wrong permissions or owner :raises OSError: if invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. zA exists, but it should be owned by current user with permissions N) rmakedirsr`errnoEEXISTcheck_permissionsr roct)r|r}r~ exceptions r!rr sw It,  ??ell *j::9dKll)2CI?@@  Lvs B ABB rhchmodcd}||f}d}tj|tjtjztj zg|}tj ||g|S)zSafely open a file. :param str path: Path to a file. :param str mode: Same os `mode` for `open`. :param int chmod: Same as `mode` for `filesystem.open`, uses Python defaults if ``None``. r)ropenrO_CREATO_EXCLO_RDWRfdopen)rhr}r open_args fdopen_argsfds r! safe_openr&s\/1I H 02K rzzBII5 A NI NB 99R , ,,r filename_patcountc  tjj|||} t|||tjj |fS#t $r(}|j t jk7rYd}~nd}~wwxYw|dz })N)rr}r<)rrhrQrabspathr`rr)rhrrrr} current_patherrs r! _unique_filer7s} ww||D,u*=>  \TBBGGOOT`Daa a yyELL()    s,A BBBcntjj|\}t|fdd||S)zSafely finds a unique file. :param str path: path/filename.ext :param int chmod: File mode :param str mode: Open mode :returns: tuple of file object and file name cd|fzS)Nz%04d_%sr)rtails r!zunique_file..Ps)udm*Cr rrrrr})rrhr-r)rhrr}rs @r! unique_filerDs5t$JD$  Cu4 ))r filenamectjj|dz} t|||fS#t$r(}|j t j k7rYd}~nd}~wwxYwt|fdd||S)aSafely finds a unique file using lineage convention. :param str path: directory path :param str filename: proposed filename :param int chmod: file mode :param str mode: open mode :returns: tuple of file object and file name (which may be modified from the requested one by appending digits to ensure uniqueness) :raises OSError: if writing files fails for an unanticipated reason, such as a full disk or a lack of permission to write to specified location. z%s.conf)rNcd|fzS)Nz %s-%04d.confr)rrs r!rz%unique_lineage_name..ls.He;L*Lr r<r)rrhrQrr`rrr)rhrrr}preferred_pathrs ` r!unique_lineage_namerTsy"WW\\$ X(>?Nu5~EE  99 $  %  Lu4 ))s5 A&A!!A&c tj|y#t$r(}|jtjk7rYd}~yd}~wwxYw)z!Remove a file that may not exist.N)rremover`rENOENT)rhrs r! safely_removerps: $  99 $  %s A AA  all_namesct}|D]} |jt||S#tj$rt j d|dYOwxYw)zRemoves names that aren't considered valid by Let's Encrypt. :param set all_names: all names found in the configuration :returns: all found names that are considered valid by LE :rtype: set zNot suggesting name "%s"Trt)setaddenforce_le_validityr ConfigurationErrorrxry)rfiltered_namesnames r!get_filtered_namesrysjUNJ J   248 9J (( J LL3TDL I Js/+AActdS)zc Get OS name and version :returns: (os_name, os_version) :rtype: `tuple` of `str` Fpretty)get_python_os_inforr r! get_os_infors U ++r ctrtjd}trsdjt dS|S)z^ Get OS name and version string for User Agent :returns: os_ua :rtype: `str` Trr[) _USE_DISTROdistrorrQr)os_infos r!get_os_info_uars4++T* gxx*$788 Nr cXtr#tjjdSgS)z Get a list of strings that indicate the distribution likeness to other distributions. :returns: List of distribution acronyms :rtype: `list` of `str` r[)rrliker-rr r!get_systemd_os_likers#{{}""3'' Ir varnamefilepathcJ|dz}tjj|syt|d5}|j }dddD]H}|j j |s#t|j t|dcSy#1swYWxYw)z Get single value from a file formatted like systemd /etc/os-release :param str varname: Name of variable to fetch :param str filepath: File path of os-release file :returns: requested value :rtype: `str` =rN) rrhisfiler readlinesstrip startswith_normalize_stringlen)rr var_stringfhcontentslines r!get_var_from_filersJ 77>>( # h "<<>"E ::< " ": .$TZZ\#j/2B%CD DE ""s BB"origcb|jddjddjS)zV Helper function for get_var_from_file() to remove quotes and whitespaces "r')replacer)rs r!rrs+ <<R ( (b 1 7 7 99r rc tjtjtjtj}|\}}}|j }|j drPtrJ|rtjntjtj}}|r|}|r|}||fS|j dra tjddgtjtjddt}|j j#d }||fS|j d r,|j%d d }|j%d d }||fStj&drtj&d}||fSd}||fS#t$rDtjddgtjtjddt}YwxYw)z Get Operating System type/distribution and major version using python platform module :param bool pretty: If the returned OS name should be in longer (pretty) form :returns: (os_name, os_version) :rtype: `tuple` of `str` rdarwinz/usr/bin/sw_versz-productVersionFT)rXrYrWrZrMsw_versr\freebsd-rr+r<r)platform system_aliassystemrwversionlowerrrrridr]r^r_rSr`rXrstrip partition win32_ver)rinfoos_typeos_verrk distro_namedistro_versionrcs r!rrs   D GVQmmoG'"{7=fkkm699;PVP^P^P`^  !G #F4 F?3   H % >>#%67!z24 D##D) F?   I &!!#&q)!!#&q) F?    a ##%a( F? F?# >>-.!z24 D sAF,,A G98G9z![a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$emailctj||jd xrd|vStj d|y)z$Scrub email address before using it.r+z..zInvalid email address: %s.F) EMAIL_REGEXmatchrrxr)rs r! safe_emailrsC+##C((>T->> LL-u5 r c 6eZdZdZ d dedededeeddf dZy) DeprecatedArgumentActionz1Action to log a warning when an argument is used.Nunused1unused2unused3 option_stringr)c0tjd|y)NzUse of %s is deprecated.)rxwarning)r2rrrrs r!__call__z!DeprecatedArgumentAction.__call__s1=Ar N)rrrrrr rrrr r!rrs<;04BBcBCB ( B9=Br r add_argument).N argument_namenargsc,ttjvr`ttjtr$tjj tntxjtfz c_||tt j|y)aAdds a deprecated argument with the name argument_name. Deprecated arguments are not shown in the help. If they are used on the command line, a warning is shown stating that the argument is deprecated and no other action is taken. :param callable add_argument: Function that adds arguments to an argument parser/group. :param str argument_name: Name of deprecated argument. :param nargs: Value for nargs when adding the argument to argparse. )actionhelprN)rconfigargparse#ACTION_TYPES_THAT_DONT_NEED_A_VALUE isinstancerrargparseSUPPRESS)rrrs r!add_deprecated_argumentrso ~'Y'YY nHH# N  > > B B( *  > >(C+ + >'?''u6r domainct|}tjd|s$tjdj ||j d}t|dkr$tjdj ||D]n}|jdr%tjdj |||jdsKtjdj |||S) ahChecks that Let's Encrypt will consider domain to be valid. :param str domain: FQDN to check :type domain: `str` :returns: The domain cast to `str`, with ASCII-only contents :rtype: str :raises ConfigurationError: for invalid domains and cases where Let's Encrypt currently will not issue certificates z^[A-Za-z0-9.-]*$zP{0} contains an invalid character. Valid characters are A-Z, a-z, 0-9, ., and -.r+z{0} needs at least two labelsrz1label "{0}" in domain "{1}" cannot start with "-"z/label "{0}" in domain "{1}" cannot end with "-") enforce_domain_sanityrerr rr@r-rrendswith)rlabelslabels r!rr1s#6 *F 88& /'' <># ++AHH6#$ $ $ Mr c^ t|tr|jd}|jd|j}|jdr|ddn|}dD]G}|jdj|s$t j d j||t|r$t j d j|d j|}t|d kDr$t j d j||jd}|D][}|s$t j dj|t|dkDs8t j dj|||S#t$rt j dwxYw)aMethod which validates domain value and errors out if the requirements are not met. :param domain: Domain to check :type domain: `str` or `bytes` :raises ConfigurationError: for invalid domains and cases where Let's Encrypt currently will not issue certificates :returns: The domain cast to `str`, with ASCII-only contents :rtype: str zutf-8asciizbNon-ASCII domain names not supported. To issue for an Internationalized Domain Name, use Punycode.r+Nr;)httphttpsz{0}://z[Requested name {0} appears to be a URL, not a FQDN. Try again without the leading "{1}://".zRequested name {0} is an IP address. The Let's Encrypt certificate authority will not issue certificates for a bare IP address.z*Requested domain {0} is not a FQDN becausez{0} it is too long.z{0} it contains an empty label.?z{0} label {1} is too long.)rrdecodeencode UnicodeErrorr rrr rr@ is_ipaddressrr-)rschemerdr ls r!r r SsL fe $]]7+F g \\^F#OOC0VCR[fF$   X__V4 5++<rGs    '"%ll%%g.    8 $* *FYFYV  zz 67 ryy{ $&S$--  %" #92::FS#X2>D\\$tCy$xt '<$eTWY\T\o$<CD& 3# 3$ 37s7#7t77&#S$SW6-C-s-#-"-" s (C5#:*> s  #& +0S>  )c )# )S )5S> ) @E$')c)S))!),1"c'N)8#c(s3x",U38_,   T#Y sc#,:C:C:3t3c3h3pbjj<= cdBxB6(9*=6c6#(c?67;66D8%U "388v#$. $uS%Z0 $T $