3 گaB@s dZddlmZddlmZddlZddlZddlZddlZddlZddl m Z ddl m Z ddl m Z ddl m Z dd l mZdd l mZdd l mZddlZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZ ddlm!Z"ddl#m$Z$ej%e&Z'e(e(dddZ)e(e(dddZ*ej+dZ,ej+dej-Z.Gdd d e"ed!Z!Gd"d#d#e e!ed!ZGd$d%d%eej/ed!Z0Gd&d'd'Z1Gd(d)d)Z2e(e(e(e e(dd*d+d,Z3e(e(ee(e(e(fd-d.d/Z4dS)0zPlugin common functions.)ABCMeta)abstractmethodN)Any)Callable)Iterable)List)Optional)Set)Tuple) achallenges) configuration) crypto_util) interfaces)errors)reverter) constants) filesystem)os) Installer)Plugin) PluginStorage)namereturncCs|dS)z9ArgumentParser options namespace (prefix of all options).-)rrr/usr/lib/python3.6/common.pyoption_namespace#srcCs|jdddS)z;ArgumentParser dest namespace (prefix of all destinations).r_)replace)rrrrdest_namespace(srzX(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)z3^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*[a-z]+$cseZdZdZejeddfdd Zee e ddddd Z ee j edd d d Zeed ddZeedddZeed ddZeedddZeedddZeejedddZZS)rzGeneric plugin.N)configrrcstj||||_||_dS)N)super__init__r r)selfr r) __class__rrr"7szPlugin.__init__.)addrcCsdS)zAdd plugin arguments to the CLI argument parser. :param callable add: Function that proxies calls to `argparse.ArgumentParser.add_argument` prepending options with unique plugin name prefix. Nr)clsr%rrradd_parser_arguments<szPlugin.add_parser_arguments)parserrrcs$tttddfdd }|j|S)zkInject parser options. See `~.certbot.interfaces.Plugin.inject_parser_options` for docs. N)arg_name_no_prefixargskwargsrcs"jdjt|f||dS)Nz--{0}{1}) add_argumentformatr)r)r*r+)rr(rrr%Osz)Plugin.inject_parser_options..add)strrr')r&r(rr%r)rr(rinject_parser_optionsGszPlugin.inject_parser_options)rcCs t|jS)z9ArgumentParser options namespace (prefix of all options).)rr)r#rrrrUszPlugin.option_namespace)rrcCs |j|S)z'Option name (include plugin namespace).)r)r#rrrr option_nameZszPlugin.option_namecCs t|jS)z;ArgumentParser dest namespace (prefix of all destinations).)rr)r#rrrr^szPlugin.dest_namespace)varrcCs|j|jddS)z.Find a destination for given variable ``var``.rr)rr)r#r1rrrdestcsz Plugin.destcCst|j|j|S)z0Find a configuration value for variable ``var``.)getattrr r2)r#r1rrrconfisz Plugin.conf)failed_achallsrcCs(djtdd|D}dj|j|dS)a9Human-readable string to help the user troubleshoot the authenticator. Shown to the user if one or more of the attempted challenges were not a success. Should describe, in simple language, what the authenticator tried to do, what went wrong and what the user should try as their "next steps". TODO: auth_hint belongs in Authenticator but can't be added until the next major version of Certbot. For now, it lives in .Plugin and auth_handler will only call it on authenticators that subclass .Plugin. For now, inherit from `.Plugin` to implement and/or override the method. :param list failed_achalls: List of one or more failed challenges (:class:`achallenges.AnnotatedChallenge` subclasses). :rtype str: z and cSsh|] }|jqSr)typ).0achallrrr sz#Plugin.auth_hint..zThe Certificate Authority couldn't externally verify that the {name} plugin completed the required {challs} challenges. Ensure the plugin is configured correctly and that the changes it makes are accessible from the internet.)rchalls)joinsortedr-r)r#r5r:rrr auth_hintmszPlugin.auth_hint).N)__name__ __module__ __qualname____doc__r ZNamespaceConfigr.r" classmethodrrr'argparseArgumentParserr/propertyrr0rr2rr4rr ZAnnotatedChallenger= __classcell__rr)r$rr4s  r) metaclasscseZdZdZeeddfdd Zdeeeedddd Z edd d d Z dd ddZ dd ddZ de ddddZeed ddZeed ddZdd ddZZS)rzAn installer base class with reverter and ssl_dhparam methods defined. Installer plugins do not have to inherit from this class. N)r*r+rcs0tj||t|j|j|_tj|j|_dS)N)r!r"rr rZstoragerZReverter)r#r*r+)r$rrr"szInstaller.__init__F) save_files save_notes temporaryrcCs\|r|jj}n|jj}y|||Wn2tjk rV}ztjt|WYdd}~XnXdS)aAdd files to a checkpoint. :param set save_files: set of filepaths to save :param str save_notes: notes about changes during the save :param bool temporary: True if the files should be added to a temporary checkpoint rather than a permanent one. This is usually used for changes that will soon be reverted. :raises .errors.PluginError: when unable to add to checkpoint N)rZadd_to_temp_checkpointadd_to_checkpointr ReverterError PluginErrorr.)r#rHrIrJZcheckpoint_funcerrrrrrKs  zInstaller.add_to_checkpoint)titlercCsHy|jj|Wn2tjk rB}ztjt|WYdd}~XnXdS)zTimestamp and save changes made through the reverter. :param str title: Title describing checkpoint :raises .errors.PluginError: when an error occurs N)rfinalize_checkpointrrLrMr.)r#rOrNrrrrPszInstaller.finalize_checkpoint)rcCsFy|jjWn2tjk r@}ztjt|WYdd}~XnXdS)zRevert all previously modified files. Reverts all modified files that have not been saved as a checkpoint :raises .errors.PluginError: If unable to recover the configuration N)rrecovery_routinerrLrMr.)r#rNrrrrQszInstaller.recovery_routinecCsFy|jjWn2tjk r@}ztjt|WYdd}~XnXdS)zkRollback temporary checkpoint. :raises .errors.PluginError: when unable to revert config N)rrevert_temporary_configrrLrMr.)r#rNrrrrRsz!Installer.revert_temporary_config)rollbackrcCsHy|jj|Wn2tjk rB}ztjt|WYdd}~XnXdS)zRollback saved checkpoints. :param int rollback: Number of checkpoints to revert :raises .errors.PluginError: If there is a problem with the input or the function is unable to correctly revert the configuration N)rrollback_checkpointsrrLrMr.)r#rTrNrrrrUs zInstaller.rollback_checkpointscCstjj|jjtjS)z(Full absolute path to ssl_dhparams file.)rpathr;r config_dirrZSSL_DHPARAMS_DEST)r#rrr ssl_dhparamsszInstaller.ssl_dhparamscCstjj|jjtjS)z:Full absolute path to digest of updated ssl_dhparams file.)rrVr;r rWrZUPDATED_SSL_DHPARAMS_DIGEST)r#rrrupdated_ssl_dhparams_digestsz%Installer.updated_ssl_dhparams_digestcCst|j|jtjtjdS)zJCopy Certbot's ssl_dhparams file into the system's config dir if required.N)install_version_controlled_filerXrYrZSSL_DHPARAMS_SRCZALL_SSL_DHPARAMS_HASHES)r#rrrinstall_ssl_dhparamss zInstaller.install_ssl_dhparams)F)rS)r>r?r@rArr"r r.boolrKrPrQrRintrUrErXrYr[rFrr)r$rrs   rc@seZdZdZdS) Configuratorzt A plugin that extends certbot.plugins.common.Installer and implements certbot.interfaces.Authenticator N)r>r?r@rArrrrr^sr^c@seZdZdZd"eeefedddZeeddddZ ed d d Z eeefd d d Z e edddZ ed ddZed ddZed ddZeddddZeeedddZed ddZeeeddd Zd!S)#AddrzRepresents an virtual host address. :param str addr: addr part of vhost address :param str port: port number or \*, or "" F)tupipv6cCs||_||_dS)N)r`ra)r#r`rarrrr"sz Addr.__init__)str_addrrcCs|jdrh|jd}|d|d}d}t||dkrX||ddkrX||dd}|||fdd S|jd}||d |dfSdS) zInitialize Addr from string.[]NrS:T)rar) startswithrfindlen partition)r&rbZendIndexhostportr`rrr fromstrings    zAddr.fromstring)rcCs|jdrd|jS|jdS)NrSz%s:%sr)r`)r#rrr__str__s  z Addr.__str__cCs|jr|j|jdfS|jS)z5Normalized representation of addr/port tuple rS)raget_ipv6_explodedr`)r#rrrnormalized_tupleszAddr.normalized_tuple)otherrcCs t||jr|j|jkSdS)NF) isinstancer$rq)r#rrrrr__eq__s z Addr.__eq__cCs t|jS)N)hashr`)r#rrr__hash__%sz Addr.__hash__cCs |jdS)z Return addr part of Addr object.r)r`)r#rrrget_addr(sz Addr.get_addrcCs |jdS)z Return port.rS)r`)r#rrrget_port,sz Addr.get_port)rmrcCs|j|jd|f|jS)z6Return new address object with same addr and new port.r)r$r`ra)r#rmrrr get_addr_obj0szAddr.get_addr_obj)addrrcCs|jd}|jd}|j|S)z7Return IPv6 address in normalized form, helper functionrcrd)lstriprstrip _explode_ipv6)r#rzrrr_normalize_ipv64s  zAddr._normalize_ipv6cCs |jrdj|j|jdSdS)zReturn IPv6 in normalized formrgrre)rar;r~r`)r#rrrrp:szAddr.get_ipv6_explodedcCsddddddddg}|jd}t|t|kr>|dt|}d}xZt|D]N\}}|s^d}qLt|dkrt|jd}|st|||<qLt|||t|<qLW|S)z#Explode IPv6 address for comparison0rgrFTrS)splitrj enumerater{r.)r#rzresultZ addr_listZ append_to_endiblockrrrr}@s   zAddr._explode_ipv6N)F)r>r?r@rAr r.r\r"rBrnrorqrrtr]rvrwrxryrr~rpr}rrrrr_sr_c@sLeZdZdZedddZd ejee ddddZ e ejd d d Z dS) ChallengePerformeravAbstract base for challenge performers. :ivar configurator: Authenticator and installer plugin :ivar achalls: Annotated challenges :vartype achalls: `list` of `.KeyAuthorizationAnnotatedChallenge` :ivar indices: Holds the indices of challenges from a larger array so the user of the class doesn't have to. :vartype indices: `list` of `int` ) configuratorcCs||_g|_g|_dS)N)rachallsindices)r#rrrrr"eszChallengePerformer.__init__N)r8idxrcCs$|jj||dk r |jj|dS)zStore challenge to be performed when perform() is called. :param .KeyAuthorizationAnnotatedChallenge achall: Annotated challenge. :param int idx: index to challenge in a larger array N)rappendr)r#r8rrrr add_challjs zChallengePerformer.add_chall)rcCs tdS)zPerform all added challenges. :returns: challenge responses :rtype: `list` of `acme.challenges.KeyAuthorizationChallengeResponse` N)NotImplementedError)r#rrrperformwszChallengePerformer.perform)N) r>r?r@rAr^r"r Z"KeyAuthorizationAnnotatedChallengerr]rrrrrrrrYs  r) dest_path digest_pathsrc_path all_hashesrc stjddfdd ddfdd }tjjsJ|dStj}|kr`dS||krp|nLtjjrtd}|j}WdQRX|krdStjddS) aCopy a file into an active location (likely the system's config dir) if required. :param str dest_path: destination path for version controlled file :param str digest_path: path to save a digest of the file in :param str src_path: path to version controlled file found in distribution :param list all_hashes: hashes of every released version of the file N)rc s$td}|jWdQRXdS)Nw)openwrite)Zfile_h) current_hashrrr_write_current_hashs z._write_current_hashcstjdS)N)shutilZcopyfiler)rrrrr_install_current_files z>install_version_controlled_file.._install_current_filerzh%s has been manually modified; updated file saved to %s. We recommend updating %s for security purposes.) r Z sha256sumrrVisfilerreadloggerZwarning)rrrrrZactive_file_digestfZ saved_digestr)rrrrrrrZs&     rZ)test_dirpkgrcCsttddd}|d}|d}|d}tj|tjtj|tjtj|tjtj|tjj d|}t j |tjj ||dd |||fS) z5Setup the directories necessary for the configurator.)prefixrcSstjtj|S)aReturn the real path of a temp directory with the specified prefix Some plugins rely on real paths of symlinks for working correctly. For example, certbot-apache uses real paths of configuration files to tell a virtual host from another. On systems where TMP itself is a symbolic link, (ex: OS X) such plugins will be confused. This function prevents such a case. )rrealpathtempfileZmkdtemp)rrrrexpanded_tempdirs z#dir_setup..expanded_tempdirZtempr ZworkZtestdataT)Zsymlinks) r.rchmodrZCONFIG_DIRS_MODE pkg_resourcesZresource_filenamerrVr;rZcopytree)rrrZtemp_dirrWZwork_dirZ test_configsrrr dir_setups r)5rAabcrrrCZloggingrerrZtypingrrrrrr r rZcertbotr r r rrrZcertbot._internalrZcertbot.compatrrZcertbot.interfacesrZAbstractInstallerrZAbstractPluginZcertbot.plugins.storagerZ getLoggerr>rr.rrcompileZprivate_ips_regex IGNORECASEZhostname_regexZ Authenticatorr^r_rrZrrrrrsT                       Thb)2