HEX
Server: LiteSpeed
System: Linux s1049.use1.mysecurecloudhost.com 4.18.0-477.27.2.lve.el8.x86_64 #1 SMP Wed Oct 11 12:32:56 UTC 2023 x86_64
User: xedaptot (3356)
PHP: 8.3.31
Disabled: NONE
Upload Files
File: //proc/self/root/lib/python3.6/site-packages/ipalib/__pycache__/util.cpython-36.pyc
3

�d[e���@s�dZddlmZmZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddl	mZddlmZddlmZddlmZddlZyddlmZWn ek
r�ddlmZYnXdd	lm Z m!Z!dd
l"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*ddl+m,Z,dd
l-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4ddl5m6Z6m7Z7ddl8m9Z9m:Z:m;Z;m<Z<ddl=m>Z>ej?d�k�r�ddl@Z@ndZ@ejA�r�eBZCdZDdZEejFeG�ZHdd�ZIdd�ZJdd�ZKdd�ZLd d!�ZMd"d#�ZNd$d%�ZOd&d'�ZPd(d)�ZQd*d+�ZRd,d-�ZSejTdddde'e(fd.d/�ZUd�d1d2�ZVd�d4d5�ZWd6d7�ZXd8d9�ZYd�d<d=�ZZd>d?�Z[d@dA�Z\dBdC�Z]dDdE�Z^dFdG�Z_dHdI�Z`dJdK�ZaejbdLejc�Zdd�d�d�d�d�d�d�d�d�d�d�d�d�d�dOdOdOdRdRdRdRdS�ZedTdU�Zfd�dYdZ�Zgd�d\d]�Zhe9jid^e9jjd_iZkd`da�Zldbdc�Zmddde�Zndfdg�ZoGdhdi�diep�ZqGdjdk�dkeq�ZrGdldm�dmeq�ZsGdndo�doeq�ZtGdpdq�dqeq�Zudrds�Zvd�dudv�Zwd�dwdx�Zxd�dydz�Zyd�d{d|�Zzd�d}d~�Z{dd��Z|d�d��Z}d�d��Z~d�d��ZGd�d��d��Z�Gd�d��d�e��Z�d�d��Z�d�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�e@dk	�r�Gd�d��d�e@j��Z�e��j�Z�ne�Z�dS)�z
Various utility functions.
�)�absolute_import�print_functionN)�	rdatatype)�DNSException)�NXDOMAIN)�AddrFormatError)�HTTPSConnection)�errors�messages)�DOMAIN_LEVEL_0�TLS_VERSIONS�TLS_VERSION_MINIMAL�TLS_VERSION_MAXIMAL�TLS_VERSION_DEFAULT_MIN�TLS_VERSION_DEFAULT_MAX)�is_ipa_client_configured)�_)�	constants)�paths)�ipautil)�SSHPublicKey)�DN�RDN)�DNSName�DNSResolver�resolve�resolve_ip_addresses)�ScriptError��z/var/lib/ipa-client/sysrestorez/etc/ipa/default.confcCs�t|ttf�rdd�|D�St|t�r8dd�|j�D�St|ttttt	d�f�rT|St|t
�rh|jd�St|tj
tf�r�t
|�Stt|dd��s�dSt|j��S)NcSsg|]}t|��qS�)�json_serialize)�.0�or r �/usr/lib/python3.6/util.py�
<listcomp>^sz"json_serialize.<locals>.<listcomp>cSsi|]\}}t|�|�qSr )r!)r"�k�vr r r$�
<dictcomp>`sz"json_serialize.<locals>.<dictcomp>zutf-8�__json__�)�
isinstance�list�tuple�dict�items�int�bool�float�unicode�type�str�decode�decimalZDecimalr�callable�getattrr!r))�objr r r$r!\s


r!cCsPyt|�stj|d��Wn2tjjk
rJ}ztj|d��WYdd}~XnXdS)N)�hostname)�	exception)rr	ZDNSNotARecordError�dnsr<rZDNSResolverError)ZfqdnZexr r r$�verify_host_resolvablems
r>cCsdyt|tj�d}Wntk
r,d}YnXyt|tj�d}Wntk
rZd}YnX|pb|S)zX
    Checks to see if given domain has SOA or NS record.
    Returns True or False.
    TF)rr�SOArZNS)�domainZsoa_record_foundZns_record_foundr r r$�has_soa_or_ns_recordvs

rAcCs�t�}|jd�}t|�dkrFt|d�j�|d<t|d�j�|d<nP|jd�}t|�dkr�t|d�j�|d<t|d�j�|d<nt|�j�|d<|S)	N�@r�r@r�name�\Zflatname)r.�split�lenr3�lower)rD�resultZ
componentsr r r$�normalize_name�s

rJcCs:dj|j��}t|�ddks.tjd|�dkr2dSdSdS)a�
    Validate the incoming data as valid base64 data or not. This is only
    used in the ipalib.Parameters module which expects ``data`` to be unicode.

    The character set must only include of a-z, A-Z, 0-9, + or / and
    be padded with = to be a length divisible by 4 (so only 0-2 =s are
    allowed). Its length must be divisible by 4. Whitespace is
    not significant so it is removed.

    This doesn't guarantee we have a base64-encoded value, just that it
    fits the base64 requirements.
    r*�rz^[a-zA-Z0-9\+\/]+\={0,2}$NFT)�joinrFrG�re�match)�datar r r$�isvalid_base64�s
rPcCsJd}|jd�}|dkr$d}|jd�}|dkrF|jd�}||||�}|S)	zM
    Remove the header and footer (and surrounding material) from a CSR.
    �(s'-----BEGIN NEW CERTIFICATE REQUEST-----rC�$s#-----BEGIN CERTIFICATE REQUEST-----rs-----END���)�find)ZcsrZ	headerlen�s�er r r$�strip_csr_header�s


rWcCsXytjtj|�Wn@tjk
rRytjtj|�Wntjk
rLdSXYnXdS)zj
    Check to see if the given IP address is a valid IPv4 or IPv6 address.

    Returns True or False
    FT)�socketZ	inet_ptonZAF_INET�errorZAF_INET6)�ipaddrr r r$�validate_ipaddr�sr[cCs�|dkrtjtd�d��yLtjj|�rPtj|tj�sbtjtd�t|d�d��nt	|d�}|j
�Wn6ttfk
r�}ztjt
|�d��WYdd}~XnXdS)zr
    Determine if the file is writable. If the file doesn't exist then
    open the file to test writability.
    NzFilename is empty)�reasonzPermission denied: %(file)s)�file�w)r	Z	FileErrorr�os�path�isfile�access�W_OKr.�open�close�IOError�OSErrorr5)�filename�fprVr r r$�check_writable_file�s
rjcCsN|st|t�r|Sd|krJ|jd�\}}}|jdd�}dj|d|f�}|S)NrB�.z\.r*)r+r5�	partition�replacerL)�zonemgrrDZ_atr@r r r$�normalize_zonemgr�srocCs|ddkr|dS|SdS)NrCrkrSr )�zoner r r$�normalize_zone�srqcCs�|dkr|dkrdS|dkr t}|dkr,t}tjt�}ytj|�}Wn$tk
rhtdj|d���YnXytj|�}Wn$tk
r�tdj|d���YnX||kr�td��||kr�|}tjd|t|�||kr�|}tjd|t|�t||d�S)	a
    This function checks whether the given TLS versions are known in
    IPA and that these versions fulfill the requirements for minimal
    TLS version (see
    `ipalib.constants: TLS_VERSIONS, TLS_VERSION_MINIMAL`).

    :param tls_version_min:
        the lower value in the TLS min-max span, raised to the lowest
        allowed value if too low
    :param tls_version_max:
        the higher value in the TLS min-max span, raised to tls_version_min
        if lower than TLS_VERSION_MINIMAL
    :raises: ValueError
    Nz5tls_version_min ('{val}') is not a known TLS version.)�valz5tls_version_max ('{val}') is not a known TLS version.z/tls_version_min is higher than tls_version_max.z5tls_version_min set too low ('%s'),using '%s' insteadz5tls_version_max set too low ('%s'),using '%s' insteadrC)r
rr�index�
ValueError�format�logger�warning)�tls_version_min�tls_version_maxZmin_allowed_idxZmin_version_idxZmax_version_idxr r r$�get_proper_tls_version_span�s8
rzcKs�tjtjtjtjtjttdd�d�}	|dkr4td��tj	j
|�sRtj|tj�rbtdj
|d���tjtj�}
|
jtjtjBtjBtjBO_tjdk	r�|
jtj�t||�}|dk	r�x<tD]4}||kr�|
j|	|M_q�|
j|	|O_q�Wt|
dd�dk	�rd	|
_tj|
_d	|
_|
j|�|dk	�rj|dk	�rXt|��}
|
j �}WdQRXnd}|
j!|||�t"||fd
|
i|��S)a]
    Create a customized HTTPSConnection object.

    :param host:  The host to connect to
    :param port:  The port to connect to, defaults to
               HTTPSConnection.default_port
    :param cafile:  A PEM-format file containning the trusted
                    CA certificates
    :param client_certfile:
            A PEM-format client certificate file that will be used to
            identificate the user to the server.
    :param client_keyfile:
            A file with the client private key. If this argument is not
            supplied, the key will be sought in client_certfile.
    :param keyfile_passwd:
            A path to the file which stores the password that is used to
            encrypt client_keyfile. Leave default value if the keyfile
            is not encrypted.
    :returns An established HTTPS connection to host:port
    Z
OP_NO_TLSv1_3r)Zssl2Zssl3ztls1.0ztls1.1ztls1.2ztls1.3NzFcafile argument is required to perform server certificate verificationz.cafile '{file}' doesn't exist or is unreadable)r]�post_handshake_authT�context)#�sslZOP_NO_SSLv2ZOP_NO_SSLv3ZOP_NO_TLSv1Z
OP_NO_TLSv1_1Z
OP_NO_TLSv1_2r9�RuntimeErrorr_r`rarb�R_OKruZ
SSLContextZPROTOCOL_TLS_CLIENTZoptionsZOP_ALLZOP_NO_COMPRESSIONZOP_SINGLE_DH_USEZOP_SINGLE_ECDH_USErZTLS_HIGH_CIPHERSZset_ciphersrzrr{Z
CERT_REQUIREDZverify_modeZcheck_hostnameZload_verify_locationsrd�readZload_cert_chainr)�host�portZcafileZclient_certfileZclient_keyfileZkeyfile_passwdrxry�kwargsZtls_cutoff_mapZctxZtls_span�versionZpwd_fZpasswdr r r$�create_https_connection&sF







r�Fc
Cs�d}d}d}|r|d7}|r$|d7}|d}dt|||d�}tj|tjtjB�}|sbttd���t|�d	krzttd
���|j|�s�dj	dd
�||D��}dj	dd
�|D��}	ttd�t||	d���dS)Nza-z0-9r*r�/�-a6^[%(base)s%(extra)s] # must begin with an alphanumeric
                                           # character, or underscore if
                                           # allow_underscore is True
        ([%(base)s%(extra)s%(middle)s]*    # can contain all allowed character
                                           # classes in the middle
        [%(base)s%(extra)s])*$             # must end with alphanumeric
                                           # character or underscore if
                                           # allow_underscore is True
        )�baseZextraZmiddlezempty DNS label�?z-DNS label cannot be longer that 63 charactersz, css|]}d|VqdS)z'%s'Nr )r"�cr r r$�	<genexpr>�sz%validate_dns_label.<locals>.<genexpr>css|]}d|VqdS)z'%s'Nr )r"r�r r r$r��sz\only letters, numbers, %(chars)s are allowed. DNS label may not start or end with %(chars2)s)�chars�chars2)
r.rM�compile�
IGNORECASE�VERBOSErtrrGrNrL)
Z	dns_label�allow_underscore�allow_slashZ
base_charsZextra_charsZmiddle_charsZlabel_regexZregexr�r�r r r$�validate_dns_label�s&

r�r@cCs\|jd�r|dd�}|jd�}t|�dkr>ttdj|����x|D]}t|||�qDWdS)NrkrCrz"single label {}s are not supportedrS)�endswithrFrGrtrrur�)Zdomain_namer�r�Zentity�labelr r r$�validate_domain_name�s


r�cCs2t|t�st�tdd�|jD��r.ttd���dS)Ncss|]}d|kVqdS)�@Nr )r"r�r r r$r��sz#validate_zonemgr.<locals>.<genexpr>ztoo many '@' characters)r+r�AssertionError�any�labelsrtr)rnr r r$�validate_zonemgr�sr�cCs t|�}t|�t|�}t|�S)N)ro�validate_idna_domainrr�)rnr r r$�validate_zonemgr_str�sr�T�cCs~t|�|krttdj|����|jd�r4|dd�}d|krHttd���d|krn|r`ttd���t|||�nt|||�dS)	a See RFC 952, 1123

    Length limit of 64 imposed by MAXHOSTNAMELEN on Linux.

    DNS and other operating systems has a max length of 255. Default to
    the theoretical max unless explicitly told to limit. The cases
    where a limit would be set might include:
     * *-install --hostname
     * ipa host-add

    The *-install commands by definition are executed on Linux hosts so
    the maximum length needs to be limited.

    :param hostname Checked value
    :param check_fqdn Check if hostname is fully qualified
    z#cannot be longer that {} charactersrkNrCz..z0hostname contains empty label (consecutive dots)znot fully qualifiedrS)rGrtrrur�r�r�)r;Z
check_fqdnr�r��maxlenr r r$�validate_hostname�s

r�cCst|�j�S)N)r�openssh)�valuer r r$�normalize_sshpubkey�sr�cCs2yt|�Wnttfk
r(td�SXdSdS)Nzinvalid SSH public key)rrt�UnicodeDecodeErrorr)�ugettextr�r r r$�validate_sshpubkey�s

r�cCsByt|�}Wnttfk
r(td�SX|j�r:td�SdSdS)Nzinvalid SSH public keyzoptions are not allowed)rrtr�rZhas_options)r�r��pubkeyr r r$�validate_sshpubkey_no_options�s
r�c
Cs�|jd�}|sdSg}g}x||D]t}yt|�}Wnttfk
rJw YnX|j�}|j�}|rld||f}d||j�f}|j|j��|j|�q Wd|kr�|p�d|d<|r�||d<dS)N�ipasshpubkeyz%s %sz%s (%s)Zsshpubkeyfp)	�getrrtr�Zfingerprint_hex_sha256�commentZkeytype�appendr�)�entry_attrsZpubkeysZ
newpubkeysZfingerprintsr�rir�r r r$�convert_sshpubkey_posts*

r�cCs*d|kpd|ks&t|dd�|jd�dS)z�
    Attribute ipasshpubkey should be added to attrs_list to be able compute
    ssh fingerprint. This attribute must be removed later if was added here
    (see remove_sshpubkey_from_output_post).
    r��*�ipasshpubkey_addedTN)�setattrr�)r|Z
attrs_listr r r$�add_sshpubkey_to_attrs_pre sr�cCs&t|dd�r"|jdd�t|d�dS)zJ
    Remove ipasshpubkey from output if it was added in pre_callbacks
    r�Fr�N)r9�pop�delattr)r|r�r r r$�!remove_sshpubkey_from_output_post+sr�cCs4t|dd�r0x|D]}|jdd�qWt|d�dS)zJ
    Remove ipasshpubkey from output if it was added in pre_callbacks
    r�Fr�N)r9r�r�)r|Zentriesr�r r r$�&remove_sshpubkey_from_output_list_post4s
r�z4([-+]?((\d+)|(\d+\.\d+)|(\.\d+)|(\d+\.)))\s*([a-z]+)im��<��rC)ZyearZyears�yZmonthZmonthsZweekZweeksr^ZdayZdays�dZhourZhours�hZminuteZminutes�min�second�secondsZsecrUcCs�d}d}x�tj|�D]z}|d7}|jd�}|jd�}|dkrBd}n4|d	krPd}n&|j�}tj|�}|d
krvtd|��t|�}||}||7}qW|dkr�td|��|S)a�

    Given a time duration string, parse it and return the total number
    of seconds represented as a floating point value. Negative values
    are permitted.

    The string should be composed of one or more numbers followed by a
    time unit. Whitespace and punctuation is optional. The numbers may
    be optionally signed.  The time units are case insenstive except
    for the single character 'M' or 'm' which means month and minute
    respectively.

    Recognized time units are:

        * year, years, y
        * month, months, M
        * week, weeks, w
        * day, days, d
        * hour, hours, h
        * minute, minutes, min, m
        * second, seconds, sec, s

    Examples:
        "1h"                    # 1 hour
        "2 HOURS, 30 Minutes"   # 2.5 hours
        "1week -1 day"          # 6 days
        ".5day"                 # 12 hours
        "2M"                    # 2 months
        "1h:15m"                # 1.25 hours
        "1h, -15min"            # 45 minutes
        "30 seconds"            # .5 minute

    Note: Despite the appearance you can perform arithmetic the
    parsing is much simpler, the parser searches for signed values and
    adds the signed value to a running total. Only + and - are permitted
    and must appear prior to a digit.

    :parameters:
        value : string
            A time duration string in the specified format
    :returns:
        total number of seconds as float (may be negative)
    rgrCr��Mr�r�r��mNzunknown time duration unit "%s"zno time duration found in "%s"i�i��i�')�time_duration_re�finditer�grouprH�time_duration_unitsr�rtr2)r�ZmatchesZdurationrNZ	magnitudeZunitZseconds_per_unitr�r r r$�parse_time_duration[s(-


r��A�AAAA�SSHFPcs.d���fdd�|D�}dj|�}|d7}|S)aj
    Generate update policy for a forward DNS zone (idnsUpdatePolicy
    attribute). Bind uses this policy to grant/reject access for client
    machines trying to dynamically update their records.

    :param realm: A realm of the of the client
    :param rrtypes: A list of resource records types that client shall be
                    allowed to update
    z&grant %(realm)s krb5-self * %(rrtype)scsg|]}�t�|d��qS))�realm�rrtype)r.)r"r�)�policy_elementr�r r$r%�sz6get_dns_forward_zone_update_policy.<locals>.<listcomp>z; �;)rL)r��rrtypes�policies�policyr )r�r�r$�"get_dns_forward_zone_update_policy�s

r��PTRcs0d����fdd�|D�}dj|�}|d7}|S)a
    Generate update policy for a reverse DNS zone (idnsUpdatePolicy
    attribute). Bind uses this policy to grant/reject access for client
    machines trying to dynamically update their records.

    :param realm: A realm of the of the client
    :param reverse_zone: Name of the actual zone. All clients with IPs in this
                         sub-domain will be allowed to perform changes
    :param rrtypes: A list of resource records types that client shall be
                    allowed to update
    z2grant %(realm)s krb5-subdomain %(zone)s %(rrtype)scsg|]}�t��|d��qS))r�rpr�)r.)r"r�)r�r��reverse_zoner r$r%�sz6get_dns_reverse_zone_update_policy.<locals>.<listcomp>z; r�)rL)r�r�r�r�r�r )r�r�r�r$�"get_dns_reverse_zone_update_policy�s
r�rK� cCst|�j�S)N)rZ
is_reverse)Z	zone_namer r r$�zone_is_reverse�sr�cCsVtjt|��}|jjd�}|jdkr2|dd�}n|jdkrH|dd�}tdj|��S)NrkrKrC��)�netaddr�	IPAddressr5Zreverse_dnsrFr�rqrL)�
ip_address�ipr/r r r$�get_reverse_zone_default�s

r�cCs:yt|�Wn$tk
r0}zt|�Sd}~XnXdSdS)N)r�	Exceptionr5)r�r�rVr r r$�validate_rdn_param�s
r�cCs4ytj|�Wnttfk
r*td�SXdSdS)Nzinvalid hostmask)r�Z	IPNetworkrtrr)r�Zhostmaskr r r$�validate_hostmask�s

r�cs"eZdZdZd�fdd�	Z�ZS)�ForwarderValidationErrorNcs(tj|||f|�tt|�j|j�dS)N)r
Zprocess_message_arguments�superr��__init__�msg)�selfru�message�kw)�	__class__r r$r��sz!ForwarderValidationError.__init__)NN)�__name__�
__module__�__qualname__rur��
__classcell__r r )r�r$r��sr�c@seZdZed�ZdS)�UnresolvableRecordErrorz&query '%(owner)s %(rtype)s': %(error)sN)r�r�r�rrur r r r$r��sr�c@seZdZed�ZdS)�EDNS0UnsupportedErrorz1query '%(owner)s %(rtype)s' with EDNS0: %(error)sN)r�r�r�rrur r r r$r��sr�c@seZdZed�ZdS)�DNSSECSignatureMissingErrorzRanswer to query '%(owner)s %(rtype)s' is missing DNSSEC signatures (no RRSIG data)N)r�r�r�rrur r r r$r�sr�c@seZdZed�ZdS)�DNSSECValidationErrorzFrecord '%(owner)s %(rtype)s' failed DNSSEC validation on server %(ip)sN)r�r�r�rrur r r r$r�sr�cCs6t|t�st�t|di�jd�}|r2tjd||�dS)z�
    If exception contains response from server, log this response to debug log
    :param log: if log is None, do not log
    :param e: DNSException
    r��responsez%DNSException: %s; server response: %sN)r+rr�r9r�rv�debug)rVr�r r r$�
_log_response
sr��
c	Cs�t|t�s|dkst�t|t�s$t�t�}|r6|g|_||_|jtjj	�|r�|j
dtjjd�tjj	}|rx|tjjB}|j|�n|r�|j
ddd�|j
||�S)z�
    :param nameserver_ip: if None, default resolvers will be used
    :param edns0: enables EDNS0
    :param dnssec: enabled EDNS0, flags: DO
    :param flag_cd: requires dnssec=True, adds flag CD
    :raise DNSException: if error occurs
    Nri)r+r5r�rZnameserversZlifetimeZ	set_flagsr=�flagsZRDZuse_ednsZDOZCDr)	�owner�rtype�
nameserver_ip�edns0�dnssec�flag_cd�timeout�resr�r r r$�_resolve_records 	r�c Cs�yt||||d�Wn:tk
rN}zt|�t||||d��WYdd}~XnXyt|||d|d�Wn:tk
r�}zt|�t||||d��WYdd}~XnXdS)z�
    Validate if forwarder supports EDNS0

    :raise UnresolvableRecordError: record cannot be resolved
    :raise EDNS0UnsupportedError: EDNS0 is not supported by forwarder
    )r�r�)r�r�r�rYNT)r�r�r�)r�rr�r�r�)r�r��ip_addrr�rVr r r$�_validate_edns0_forwarder7s
rcCs�t|�}d}d}t||||d�yt|||d|d�}Wn8tk
rn}zt|�t|||d��WYdd}~XnXy,|jj|jjt	j
jt	jj
t	jjt	jj�Wn"tk
r�t|||d��YnXdS)aETest DNS forwarder properties. against root zone.

    Global forwarders should be able return signed root zone

    :raise UnresolvableRecordError: record cannot be resolved
    :raise EDNS0UnsupportedError: EDNS0 is not supported by forwarder
    :raise DNSSECSignatureMissingError: did not receive RRSIG for root zone
    rkr?)r�T)r�r�r�)r�r�r�N)r5rr�rr�r�r�Z
find_rrset�answerr=rD�rootZ
rdataclass�INrZRRSIGr?�KeyError)rr�r�r�ZansrVr r r$� validate_dnssec_global_forwarderOs 

 rcCst|d||d�dS)z�
    Only forwarders in forward zones can be validated in this way
    :raise UnresolvableRecordError: record cannot be resolved
    :raise EDNS0UnsupportedError: ENDS0 is not supported by forwarder
    r?)r�N)r)r�fwzoner�r r r$�$validate_dnssec_zone_forwarder_step1psrcCsd}yt|||ddd|d�}Wnptk
rV}zt|�t|||d��WYdd}~Xn:tk
r�}zt|�t||||d��WYdd}~XnXyt|||dd|d�}Wn8tk
r�}zt|�t|||d��WYdd}~Xn,X|j|jkr�|j|jkr�dSt|||d��dS)a�
    This step must be executed after forwarders are added into LDAP, and only
    when we are sure the forwarders work.
    Query will be send to IPA DNS server, to verify if reply passed,
    or DNSSEC validation failed.
    Only forwarders in forward zones can be validated in this way
    :raise UnresolvableRecordError: record cannot be resolved
    :raise DNSSECValidationError: response from forwarder is not DNSSEC valid
    r?T)r�r�r�r�r�)r�r�r�N)r�r�r�rY)r�r�r�r�)r�rr�r�rr�Zcanonical_nameZrrset)Zipa_ip_addrrr�r�Zans_cdrVZans_dor r r$�$validate_dnssec_zone_forwarder_step2ys,
 r	cCs<d}yt|�Wn�tjjk
r0td�}Yn�tjjk
rNtd�}Yn�tjjk
rltd�}Yn�tjjk
r�td�}Yn�tjj	k
r�td�}Yn�Xt
jd|t
jd�}yx|D]}|j
d	�q�WWnPtk
�r(td
d�|D��}|�r$td�|d
jdd�|D��d�}YnX|�r8t|��dS)z
    Validate if value is valid IDNA domain.

    If domain is not valid, raises ValueError
    :param value:
    :return:
    Nz"invalid escape code in domain namezempty DNS labelz0domain name cannot be longer than 255 charactersz-DNS label cannot be longer than 63 characterszinvalid domain nameu[..。。])r��asciicss|]}tjj|�|kVqdS)N)�	encodings�idna�nameprep)r"�xr r r$r��sz'validate_idna_domain.<locals>.<genexpr>z@domain name '%(domain)s' should be normalized to: %(normalized)srkcSsg|]}tjj|��qSr )rrr
)r"rr r r$r%�sz(validate_idna_domain.<locals>.<listcomp>)r@Z
normalized)rr=rDZ	BadEscaperZ
EmptyLabelZNameTooLongZLabelTooLongr<�SyntaxErrorrMrF�UNICODE�encode�UnicodeErrorr�rLrt)r�rYr�r�Z
is_nonnormr r r$r��s4

r�c
Cs�td�}t|�}||}ynt|tj�}|jj}t|�dkr�t|d�dkr�|djtjkr�|dd}|j�dj	|j
j�kr�dSdSWntk
r�YnXtd�}||}	yt|	tj
�Wntk
r�dSXdSd	S)
aP
    Detects the type of the realm that the given DNS zone belongs to.
    Note: This method is heuristic. Possible values:
      - 'current': For IPA domains belonging in the current realm.
      - 'foreign': For domains belonging in a foreing kerberos realm.
      - 'unknown': For domains whose allegiance could not be detected.
    Z	_kerberosrCrz"{0}"ZcurrentZforeignz_ldap._tcp.gc._msdcs�unknownN)rrrZTXTr�rrGZrdtypeZto_textru�envr�rZSRV)
�apir@Zkerberos_prefixZ
domain_suffixZkerberos_record_namerIr�recordZ	gc_prefixZad_specific_record_namer r r$�detect_dns_zone_realm_type�s,rcCs|jd�jdt�}|tkS)NZdomainlevel_getrI)�Commandr�r)rZdomainlevelr r r$�has_managed_topologysrcCs�|r||jjd�}|dk	r@td|�tdttj|jd���|jjd�}|dk	r|td|�tdttj|jd	���dS)
z�Pretty print nsds5replicalastinitstatus, nsds5replicalastinitend,
    nsds5replicalastupdatestatus, nsds5replicalastupdateend for a
    replication agreement.
    Znsds5replicalastinitstatusNz  last init status: %sz  last init ended: %sZnsds5replicalastinitendZnsds5replicalastupdatestatusz  last update status: %sz  last update ended: %sZnsds5replicalastupdateend)�single_valuer��printr5rZparse_generalized_time)�entry�verboseZ
initstatusZupdatestatusr r r$�print_replication_statussrc@s:eZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�
classproperty�__doc__�fgetNcCs4t|t�st�|dkr$|dk	r$|j}||_||_dS)N)r+�classmethodr�r r!)r�r!�docr r r$r�"s
zclassproperty.__init__cCs&|jdk	r|jj||��Std��dS)Nzunreadable attribute)r!�__get__�AttributeError)r�r:�obj_typer r r$r$*s
zclassproperty.__get__cCstd��dS)Nzcan't set attribute)r%)r�r:r�r r r$�__set__/szclassproperty.__set__cCstd��dS)Nzcan't delete attribute)r%)r�r:r r r$�
__delete__2szclassproperty.__delete__cCs
||_|S)N)r!)r�r!r r r$�getter5szclassproperty.getter)r r!)NN)	r�r�r��	__slots__r�r$r'r(r)r r r r$rs
rc@seZdZdZdd�ZdS)�classobjectpropertyr cCs(|jdk	r|jj||�|�Std��dS)Nzunreadable attribute)r!r$r%)r�r:r&r r r$r$?s
zclassobjectproperty.__get__N)r )r�r�r�r*r$r r r r$r+:sr+cCs"|jd�r|dd�}|j�}|S)z-Use common fqdn form without the trailing dotrkNrCrS)r�rH)r;r r r$�normalize_hostnameEs
r,cCsByt||d�Wn,tk
r<}ztd�t|�Sd}~XnXdS)aValidator used by plugins to ensure hostname compliance.

       In Linux the maximum hostname length is 64. In DNS and
       other operaring systems (Solaris) it is 255. If not explicitly
       checking a Linux hostname (e.g. the server) use the DNS
       default.
    )r�zinvalid domain-name: %sN)r�rtrr3)r�r�r�rVr r r$�hostname_validatorMs
r-cCsdy@tjt|�tjd�}|dk	r>|j|kr>td�t|j|d�SWntjtfk
r^td�SXdS)N)r�zFinvalid IP address version (is %(value)d, must be %(required_value)d)!)r�Zrequired_valuezinvalid IP address format)	r�r�r5Z	INET_PTONr�rr.rrt)r�rZZ
ip_versionr�r r r$�ipaddr_validator]s

r.cCst|jd�\}}}t||�}|dk	r&|S|rpy"t|�}|dksD|dkrJt��Wn"tk
rntdt|d��SXdS)Nz port ri��z%(port)s is not a valid port)r�)rlr.r0rtrr.)r�Z	forwarderr��sepr�Zip_address_validationr r r$�validate_bind_forwarderns

r0cCsBtdd�|dD��}d|kr"dSd|kr>d|kr>|d|d<dS)Ncss|]}|j�VqdS)N)rH)r"�ir r r$r��sz'set_krbcanonicalname.<locals>.<genexpr>�objectclassZkrbprincipalaux�krbprincipalname�krbcanonicalname)�set)r�Z
objectclassesr r r$�set_krbcanonicalname�sr6cGsB|j|jddg�}|jjdd�}||dkr>tjdtd�d��dS)a	
    ensure that the LDAP entry has at least one value of krbprincipalname
    and that this value is equal to krbcanonicalname

    :param ldap: LDAP connection object
    :param entry_attrs: LDAP entry made prior to update
    :param options: command options
    r4r3NrCzHat least one value equal to the canonical principal name must be present)rDrYrS)�	get_entry�dnrr�r	�ValidationErrorr)�ldapr��keysrr4r r r$�ensure_last_krbprincipalname�s	r<cCsX|j|jdddg�}|jjdd�dk	r*dSt|�|jdd�|jdd�|j|�dS)Nr4r3r2)r7r8rr�r6r��update)r:r�Z	old_entryr r r$�ensure_krbcanonicalname_set�sr>cCs^d}|dk	rF|jtjkrFtjj|j�r*dStd|j�d|j�d�|��t�rPdStd|��dS)a 
    Check if IPA client is configured on the system.

    This is a convenience wrapper that also supports using
    a custom configuration via IPA_CONFDIR.

    Raises a ScriptError exception if the client is not
    configured.

    Hardcode return code to avoid recursive imports
    rNTz5IPA client is not configured on this system (confdir z is missing �)z+IPA client is not configured on this system)	ZconfdirrZETC_IPAr_r`raZconf_defaultrr)rZCLIENT_NOT_CONFIGUREDr r r$�check_client_configuration�sr@c	Gs�|jjddd�d}t�}xd|D]\}|jdg�}|jtdd�|D���d|krf|j|ddj��|j|d	dj��q WxH|dD]<}|j}|jr�|j	nd}||ks�||kr�t
jdtd
�d��q�WdS)a7
    Check that principal name's suffix does not overlap with UPNs and realm
    names of trusted forests.

    :param api_instance: API instance
    :param suffixes: principal suffixes

    :raises: ValidationError if the suffix coincides with realm name, UPN
    suffix or netbios name of trusted domains
    r*r)Z	sizelimitrIZipantadditionalsuffixescss|]}|j�VqdS)N)rH)r"�upnr r r$r��sz;check_principal_realm_in_trust_namespace.<locals>.<genexpr>Z
ipantflatnameZcnrCNr3z:realm or UPN suffix overlaps with trusted domain namespace)rDrYrS)
rZ
trust_findr5r�r=�addrHr�Z
is_enterpriseZ
upn_suffixr	r9r)	Zapi_instancer;Z
trust_objectsZtrust_suffix_namespacer:Znt_suffixesZ	principalr�rAr r r$�(check_principal_realm_in_trust_namespace�s 
rCcCs:x4|D],}|j�stjd|�tdj|�tjd�qWdS)Nz.No network interface matches the IP address %sz7WARNING: No network interface matches the IP address {})r])Zget_matching_interfacervrwrru�sys�stderr)Z	addr_listr�r r r$�,no_matching_interface_for_ip_address_warning�s
rFc
CsHytjdtj|tjd��dStttjfk
rBt	j
jdd�SXdS)z�
    Get current terminal height

    Args:
        fd (int): file descriptor. Default: 1 (stdout)

    Returns:
        int: Terminal height
    Zhhs1234rZLINES�N)�struct�unpack�fcntlZioctl�termiosZ
TIOCGWINSZrfrgrYr_�environr�)�fdr r r$�get_terminal_heights

rNcCstjjdd�}tj|�S)zl Get path to a pager

    :return: path to the file if it exists otherwise None
    :rtype: str or None
    ZPAGERZless)r_rLr��shutilZwhich)�pagerr r r$�	get_pagersrQcCsDtj|gtjd�}y|jj|�|j�Wntk
r>YnXdS)z�
    Open text data in pager

    Args:
        data (bytes): data to view in pager
        pager (str): path to the pager

    Returns:
        None
    )�stdinN)�
subprocess�Popen�PIPErR�writeZcommunicaterf)rOrPZ
pager_processr r r$�
open_in_pager!srWcsJeZdZeeeeeee	e
eee
d�hZ�fdd�Zdd�Zdd�Z�ZS)�APIReprNcsBtt|�j�x.|jj�D] \}}t|t�rt||tj	�qWdS)N)
r�rXr��__dict__r/r+r0r�rD�maxsize)r�r&r')r�r r$r�>s
zAPIRepr.__init__cCsdt|�S)zOutput with u'' prefix�u)�repr)r�r�levelr r r$�repr_strEszAPIRepr.repr_strcCs.|tkrdS||jkr"dj|j�St|�SdS)Nz<type 'unicode'>z<type '{}'>)r5�
builtin_typesrur�r\)r�rr]r r r$�	repr_typeIs

zAPIRepr.repr_type)r�r�r�r1r0r2r5�bytesr.r-r,r5�	frozensetr4r_r�r^r`r�r r )r�r$rX6s

rX)rr)FF)FFr@)TFFr�i8"i i�3�i8"i i�3�i8"i i�3�i�i��i�'i�i��i�'�i`'i�:	rci`'i�:	rci`'i�:	i�i�Qi�i�Qi�i�Qiii�r�r�r�)rd�r�)re)NFFFr�)r�)r�)r�)r�)r�)N)N)rC)�r Z
__future__rrZloggingr_rXrMr7r=rrDr}rKrJrOrHrSr�rZ
dns.exceptionrZdns.resolverrZnetaddr.corerZsixZhttplibr�ImportErrorZhttp.clientZipalibr	r
Zipalib.constantsrrr
rrrZipalib.factsrZipalib.textrZipaplatform.constantsrZipaplatform.pathsrZ	ipapythonrZ
ipapython.sshrZipapython.dnrrZipapython.dnsutilrrrrZipapython.admintoolr�version_info�reprlibZPY3r5r3Z_IPA_CLIENT_SYSRESTOREZ_IPA_DEFAULT_CONFZ	getLoggerr�rvr!r>rArJrPrWr[rjrorqrzZdefault_portr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�Zip4_rev_zoneZip6_rev_zoneZREVERSE_DNS_ZONESr�r�r�r�r�r�r�r�r�r�r�r�rrrr	r�rrrrr+r,r-r.r0r6r<r>r@rCrFrNrQrW�ReprrXr\Zapireprr r r r$�<module>s 

	5X
&

"		G


		
 

!
	
(,4


!%