HEX
Server: LiteSpeed
System: Linux shams.tasjeel.ae 5.14.0-611.5.1.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Tue Nov 11 08:09:09 EST 2025 x86_64
User: infowars (1469)
PHP: 8.2.29
Disabled: NONE
Upload Files
File: //usr/lib/python3.9/site-packages/ipalib/__pycache__/util.cpython-39.opt-1.pyc
a

}�f���@s�dZddlmZmZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddl	mZddlmZddlmZddlmZddlZzddlmZWney�ddlmZYn0dd	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>ddl?m@Z@ejAdk�r�ddlBZBndZBejC�r�eDZEdZFdZGe�HeI�ZJdd�ZKdd�ZLdd�ZMdd�ZNd d!�ZOd"d#�ZPd$d%�ZQd&d'�ZRd(d)�ZSd*d+�ZTd,d-�ZUejVdddde'e(fd.d/�ZWd�d1d2�ZXd�d4d5�ZYd6d7�ZZd8d9�Z[d�d<d=�Z\d>d?�Z]d@dA�Z^dBdC�Z_dDdE�Z`dFdG�ZadHdI�ZbdJdK�Zce�ddLeje�ZfdMdMdMdNdNdOdOdOdPdPdPdQdQdQdRdRdRdSdSdSdSdT�ZgdUdV�Zhd�dXdY�Zid�d[d\�Zje9jkd]e9jld^iZmd_d`�Zndadb�Zodcdd�Zpdedf�ZqGdgdh�dher�ZsGdidj�djes�ZtGdkdl�dles�ZuGdmdn�dnes�ZvGdodp�dpes�Zwdqdr�Zxd�dtdu�Zyd�dvdw�Zzd�dxdy�Z{d�dzd{�Z|d�d|d}�Z}d~d�Z~d�d��Zd�d��Z�d�d��Z�Gd�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�d��Z�d�d��d�d��Z�d�d��d�d��Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�eBdu�r�Gd�d��d�eBj��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)�	Principal)��z/var/lib/ipa-client/sysrestorez/etc/ipa/default.confcCs�t|ttf�rdd�|D�St|t�r8dd�|��D�St|ttttt	d�f�rT|St|t
�rh|�d�St|tj
tf�r�t
|�Stt|dd��s�dSt|���S)NcSsg|]}t|��qS���json_serialize)�.0�or!r!�//usr/lib/python3.9/site-packages/ipalib/util.py�
<listcomp>_�z"json_serialize.<locals>.<listcomp>cSsi|]\}}|t|��qSr!r")r$�k�vr!r!r&�
<dictcomp>ar(z"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#c
CsRzt|�stj|d��Wn4tjjyL}ztj|d��WYd}~n
d}~00dS)N��hostname)�	exception)rr	ZDNSNotARecordError�dnsr@rZDNSResolverError)Zfqdn�exr!r!r&�verify_host_resolvablens
rCcCs`zt|tj�d}Wnty*d}Yn0zt|tj�d}WntyVd}Yn0|p^|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_recordws

rFcCs�t�}|�d�}t|�dkrFt|d���|d<t|d���|d<nP|�d�}t|�dkr�t|d���|d<t|d���|d<nt|���|d<|S)	N�@r �rEr�name�\Zflatname)r1�split�lenr6�lower)rI�result�
componentsr!r!r&�normalize_name�s

rPcCs:d�|���}t|�ddks.t�d|�dur2dSdSdS)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)�joinrKrL�re�match)�datar!r!r&�isvalid_base64�s�rVcCsJd}|�d�}|dkr$d}|�d�}|dkrF|�d�}||||�}|S)zM
    Remove the header and footer (and surrounding material) from a CSR.
    �(s'-----BEGIN NEW CERTIFICATE REQUEST-----����$s#-----BEGIN CERTIFICATE REQUEST-----rs-----END)�find)ZcsrZ	headerlen�s�er!r!r&�strip_csr_header�s


r]cCsXzt�tj|�Wn@tjyRzt�tj|�WntjyLYYdS0Yn0dS)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�srac
Cs�|durtjtd�d��zLtj�|�rPt�|tj�sbtjtd�t|d�d��nt	|d�}|�
�Wn8ttfy�}ztjt
|�d��WYd}~n
d}~00dS)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_OKr1�open�close�IOError�OSErrorr8)�filename�fpr\r!r!r&�check_writable_file�s
rqcCsJ|rt|t�s|Sd|vrF|�d�\}}}|�dd�}d�|d|f�}|S)NrG�.z\.r-)r.r8�	partition�replacerR)�zonemgrrIZ_atrEr!r!r&�normalize_zonemgr�srvcCs|ddkr|dS|SdS)NrXrrr!)�zoner!r!r&�normalize_zone�srxcCs�|dur|durdS|dur t}|dur,t}t�t�}zt�|�}Wn"tyftdj|d���Yn0zt�|�}Wn"ty�tdj|d���Yn0||kr�td��||kr�|}t�d|t|�||kr�|}t�d|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' insteadrH)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�s@
����r�c	Ks�tjtjtjtjtjttdd�d�}	|dur4td��tj	�
|�rNt�|tj�s^tdj
|d���t�tj�}
|
jtjtjBtjBtjBO_tjdur�|
�tj�t||�}|dur�tD]4}||vr�|
j|	|M_q�|
j|	|O_q�t|
dd�du�rd	|
_tj|
_d	|
_|
�|�|du�rx|du�rft|��}
|
� �}Wd�n1�sZ0Ynd}|
�!|||�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 unreadablerc�post_handshake_authT�context)#�sslZOP_NO_SSLv2ZOP_NO_SSLv3ZOP_NO_TLSv1Z
OP_NO_TLSv1_1Z
OP_NO_TLSv1_2r<�RuntimeErrorrfrgrhri�R_OKr|Z
SSLContextZPROTOCOL_TLS_CLIENT�optionsZOP_ALLZOP_NO_COMPRESSIONZOP_SINGLE_DH_USEZOP_SINGLE_ECDH_USErZTLS_HIGH_CIPHERSZset_ciphersr�rr�Z
CERT_REQUIREDZverify_modeZcheck_hostnameZload_verify_locationsrk�readZload_cert_chainr)�host�portZcafileZclient_certfileZclient_keyfileZkeyfile_passwdrr��kwargsZtls_cutoff_map�ctxZtls_span�versionZpwd_f�passwdr!r!r&�create_https_connection'sN
�	���





*r�Fc
Cs�d}d}d}|r|d7}|r$|d7}|d}dt|||d�}t�|tjtjB�}|sbttd���t|�d	krzttd
���|�|�s�d�	dd
�||D��}d�	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
        )�baseZextraZmiddle�empty DNS label�?z-DNS label cannot be longer that 63 charactersz, css|]}d|VqdS�z'%s'Nr!�r$�cr!r!r&�	<genexpr>�r(z%validate_dns_label.<locals>.<genexpr>css|]}d|VqdSr�r!r�r!r!r&r��r(z\only letters, numbers, %(chars)s are allowed. DNS label may not start or end with %(chars2)s)�chars�chars2)
r1rS�compile�
IGNORECASE�VERBOSEr{rrLrTrR)
Z	dns_label�allow_underscore�allow_slashZ
base_charsZextra_charsZmiddle_charsZlabel_regexZregexr�r�r!r!r&�validate_dns_label�s,�	

�r�rEcCsX|�d�r|dd�}|�d�}t|�dkr>ttd�|����|D]}t|||�qBdS)NrrrXr z"single label {}s are not supported)�endswithrKrLr{rr|r�)Zdomain_namer�r�Zentity�labelr!r!r&�validate_domain_name�s

�r�cCs$tdd�|jD��r ttd���dS)Ncss|]}d|vVqdS)�@Nr!)r$r�r!r!r&r��r(z#validate_zonemgr.<locals>.<genexpr>ztoo many '@' characters)�any�labelsr{r�rur!r!r&�validate_zonemgr�sr�cCs t|�}t|�t|�}t|�S�N)rv�validate_idna_domainrr�r�r!r!r&�validate_zonemgr_str�sr�T�cCs~t|�|krttd�|����|�d�r4|dd�}d|vrHttd���d|vrn|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 {} charactersrrNrXz..z0hostname contains empty label (consecutive dots)znot fully qualified)rLr{rr|r�r�r�)r?Z
check_fqdnr�r��maxlenr!r!r&�validate_hostname�s�
r�cCst|���Sr�)r�openssh)�valuer!r!r&�normalize_sshpubkey�sr�c	Cs4zt|�Wnttfy*td�YS0dSdS)N�invalid SSH public key)rr{�UnicodeDecodeErrorr)�ugettextr�r!r!r&�validate_sshpubkey�s
r�c	CsDzt|�}Wnttfy*td�YS0|��r<td�SdSdS)Nr�zoptions are not allowed)rr{r�rZhas_options)r�r��pubkeyr!r!r&�validate_sshpubkey_no_options�sr�c
Cs�|�d�}|sdSg}g}|D]t}zt|�}WnttfyHYqYn0|��}|��}|rjd||f}d||��f}|�|���|�|�qd|vr�|p�d|d<|r�||d<dS)N�ipasshpubkeyz%s %sz%s (%s)Zsshpubkeyfp)	�getrr{r�Zfingerprint_hex_sha256�commentZkeytype�appendr�)�entry_attrsZpubkeysZ
newpubkeysZfingerprintsr�rpr�r!r!r&�convert_sshpubkey_posts*

r�cCs*d|vs&d|vs&t|dd�|�d�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"|�dd�t|d�dS�zJ
    Remove ipasshpubkey from output if it was added in pre_callbacks
    r�Fr�N�r<�pop�delattr)r�r�r!r!r&�!remove_sshpubkey_from_output_post,sr�cCs0t|dd�r,|D]}|�dd�qt|d�dSr�r�)r��entriesr�r!r!r&�&remove_sshpubkey_from_output_list_post5sr�z4([-+]?((\d+)|(\d+\.\d+)|(\.\d+)|(\d+\.)))\s*([a-z]+)i�3���'i�:	i�Qi�<rH)ZyearZyears�yZmonthZmonthsZweekZweeksreZdayZdays�dZhourZhours�hZminuteZminutes�min�second�secondsZsecr[cCs�d}d}t�|�D]z}|d7}|�d�}|�d�}|dkr@d}n4|dkrNd}n&|��}t�|�}|d	urttd
|��t|�}||}||7}q|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)
    rgrH��Mr��mr�Nzunknown time duration unit "%s"zno time duration found in "%s")�time_duration_re�finditer�grouprM�time_duration_unitsr�r{r5)r��matchesZdurationrTZ	magnitudeZunitZseconds_per_unitr�r!r!r&�parse_time_duration\s(-



r���AZAAAAZSSHFPcs.d���fdd�|D�}d�|�}|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�r1�r$r���policy_elementr�r!r&r'�s�z6get_dns_forward_zone_update_policy.<locals>.<listcomp>�; �;�rR)r��rrtypes�policies�policyr!r�r&�"get_dns_forward_zone_update_policy�s
�
r��ZPTRcs0d����fdd�|D�}d�|�}|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�rwr�r�r��r�r��reverse_zoner!r&r'�s��z6get_dns_reverse_zone_update_policy.<locals>.<listcomp>r�r�r�)r�r�r�r�r�r!r�r&�"get_dns_reverse_zone_update_policy�s�
r�rQ� cCst|���Sr�)rZ
is_reverse)Z	zone_namer!r!r&�zone_is_reverse�sr�cCsVt�t|��}|j�d�}|jdkr2|dd�}n|jdkrH|dd�}td�|��S)NrrrQrH��)�netaddr�	IPAddressr8Zreverse_dnsrKr�rxrR)�
ip_address�ipr2r!r!r&�get_reverse_zone_default�s

r�c
CsBzt|�Wn,ty8}zt|�WYd}~Sd}~00dSdSr�)r�	Exceptionr8)r�r�r\r!r!r&�validate_rdn_param�s
r�c	Cs6zt�|�Wnttfy,td�YS0dSdS)Nzinvalid hostmask)r�Z	IPNetworkr{rr)r��hostmaskr!r!r&�validate_hostmask�s
r�cs"eZdZdZd�fdd�	Z�ZS)�ForwarderValidationErrorNcs,tj|||fi|��tt|��|j�dSr�)r
Zprocess_message_arguments�superr��__init__�msg)�selfr|�message�kw��	__class__r!r&r��sz!ForwarderValidationError.__init__)NN)�__name__�
__module__�__qualname__r|r��
__classcell__r!r!rr&r��sr�c@seZdZed�ZdS)�UnresolvableRecordErrorz&query '%(owner)s %(rtype)s': %(error)sN�rrrrr|r!r!r!r&r�src@seZdZed�ZdS)�EDNS0UnsupportedErrorz1query '%(owner)s %(rtype)s' with EDNS0: %(error)sNrr!r!r!r&r	�sr	c@seZdZed�ZdS)�DNSSECSignatureMissingErrorzRanswer to query '%(owner)s %(rtype)s' is missing DNSSEC signatures (no RRSIG data)Nrr!r!r!r&r
sr
c@seZdZed�ZdS)�DNSSECValidationErrorzFrecord '%(owner)s %(rtype)s' failed DNSSEC validation on server %(ip)sNrr!r!r!r&rsrcCs(t|di��d�}|r$t�d||�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<r�r}�debug)r\rr!r!r&�
_log_responsesr�
c	Cs~t�}|r|g|_||_|�tjj�|r`|�dtjjd�tjj}|rT|tjj	B}|�|�n|rr|�ddd�|�
||�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
    ri)rZnameserversZlifetimeZ	set_flagsrA�flagsZRDZuse_ednsZDOZCDr)	�owner�rtype�
nameserver_ip�edns0�dnssec�flag_cd�timeout�resrr!r!r&�_resolve_recordsrc
Cs�zt||||d�Wn<tyP}z$t|�t||||d��WYd}~n
d}~00zt|||d|d�Wn<ty�}z$t|�t||||d��WYd}~n
d}~00dS)z�
    Validate if forwarder supports EDNS0

    :raise UnresolvableRecordError: record cannot be resolved
    :raise EDNS0UnsupportedError: EDNS0 is not supported by forwarder
    )rr�rrr�r_NT)rrr)rrrrr	)rr�ip_addrrr\r!r!r&�_validate_edns0_forwarder8s �
�
�rc
Cs�t|�}d}d}t||||d�zt|||d|d�}Wn:typ}z"t|�t|||d��WYd}~n
d}~00z,|j�|jjt	j
jt	jj
t	jjt	jj�Wn ty�t|||d��Yn0dS)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
    rrrD�rT)rrr�rrr�N)r8rrrrr
rZ
find_rrset�answerrArI�rootZ
rdataclass�INrZRRSIGrD�KeyError)rrrrZansr\r!r!r&� validate_dnssec_global_forwarderPs$

�
$�r#cCst|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
    rDrN)r)r�fwzonerr!r!r&�$validate_dnssec_zone_forwarder_step1qsr%c
Csd}zt|||ddd|d�}WnttyX}z"t|�t|||d��WYd}~nDd}~0ty�}z$t|�t||||d��WYd}~n
d}~00zt|||dd|d�}Wn:ty�}z"t|�t|||d��WYd}~n8d}~00|j|jk�r|j|jk�rdSt|||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
    rDT)rrrrrrNr)rrrr)rrrrrrZcanonical_nameZrrset)Zipa_ip_addrr$rrZans_cdr\Zans_dor!r!r&�$validate_dnssec_zone_forwarder_step2zs4
�
"��
$
�r&c	Cs,d}zt|�Wn�tjjy.td�}Yn�tjjyJtd�}Yn�tjjyftd�}Yn�tjjy�td�}Yn�tjj	y�td�}Yn|0t
jd|t
jd�}z|D]}|�
d	�q�WnNt�ytd
d�|D��}|�rtd�|d
�dd�|D��d�}Yn0|�r(t|��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 namer�z0domain name cannot be longer than 255 charactersz-DNS label cannot be longer than 63 characterszinvalid domain nameu[..。。]�r�asciicss|]}tj�|�|kVqdSr���	encodingsZidnaZnameprep�r$�xr!r!r&r��r(z'validate_idna_domain.<locals>.<genexpr>z@domain name '%(domain)s' should be normalized to: %(normalized)srrcSsg|]}tj�|��qSr!r)r+r!r!r&r'�s�z(validate_idna_domain.<locals>.<listcomp>)rEZ
normalized)rrArIZ	BadEscaperZ
EmptyLabelZNameTooLongZLabelTooLongr@�SyntaxErrorrSrK�UNICODE�encode�UnicodeErrorr�rRr{)r�r_r�r�Z
is_nonnormr!r!r&r��s:
���
r�c
Cs�td�}t|�}||}zrt|tj�}|jj}t|�dkr�t|d�dkr�|djtjkr�|dd}|��d�	|j
j�kr�WdSWdSWnty�Yn0td�}||}	zt|	tj
�Wnty�YdS0dSd	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	_kerberosrHrz"{0}"�currentZforeignz_ldap._tcp.gc._msdcs�unknownN)rrrZTXTrrrLZrdtypeZto_textr|�envr�rZSRV)
�apirEZkerberos_prefixZ
domain_suffixZkerberos_record_namerNr�recordZ	gc_prefixZad_specific_record_namer!r!r&�detect_dns_zone_realm_type�s0��
r6cCs|jd��dt�}|tkS)NZdomainlevel_getrN)�Commandr�r)r4Zdomainlevelr!r!r&�has_managed_topologysr8cCs�|r||j�d�}|dur@td|�tdtt�|jd���|j�d�}|dur|td|�tdtt�|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��printr8rZparse_generalized_time)�entry�verboseZ
initstatusZupdatestatusr!r!r&�print_replication_statuss&�����r=c@s:eZdZdZd
dd�Zdd�Zdd�Zd	d
�Zdd�ZdS)�
classproperty��__doc__�fgetNcCs&|dur|dur|j}||_||_dSr�r?)r�rA�docr!r!r&r�#szclassproperty.__init__cCs&|jdur|j�||��Std��dS�Nzunreadable attribute�rA�__get__�AttributeError�r�r=Zobj_typer!r!r&rE+s
zclassproperty.__get__cCstd��dS)Nzcan't set attribute�rF)r�r=r�r!r!r&�__set__0szclassproperty.__set__cCstd��dS)Nzcan't delete attributerH)r�r=r!r!r&�
__delete__3szclassproperty.__delete__cCs
||_|Sr�)rA)r�rAr!r!r&�getter6szclassproperty.getter)NN)	rrr�	__slots__r�rErIrJrKr!r!r!r&r> s
r>c@seZdZdZdd�ZdS)�classobjectproperty)r@cCs(|jdur|j�||�|�Std��dSrCrDrGr!r!r&rE@s
zclassobjectproperty.__get__N)rrrrLrEr!r!r!r&rM;srMcCs"|�d�r|dd�}|��}|S)z-Use common fqdn form without the trailing dotrrNrX)r�rMr>r!r!r&�normalize_hostnameFs
rNc
CsJzt||d�Wn4tyD}ztd�t|�WYd}~Sd}~00dS)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�r{rr6)r�r�r�r\r!r!r&�hostname_validatorNs
&rOc	CshzBtjt|�tjd�}|dur@|j|kr@td�t|j|d�WSWn tjtfybtd�YS0dS)Nr'zFinvalid IP address version (is %(value)d, must be %(required_value)d)!)r�Zrequired_valuezinvalid IP address format)	r�r�r8Z	INET_PTONr�rr1rr{)r�r`Z
ip_versionr�r!r!r&�ipaddr_validator^s
���
rPcCsv|�d�\}}}t||�}|dur&|S|rrz"t|�}|dksD|dkrJt��Wn$typtdt|d��YS0dS)Nz port ri��z%(port)s is not a valid port)r�)rsrPr3r{rr1)r�Z	forwarderr��sepr�Zip_address_validationr!r!r&�validate_bind_forwarderos

rRcCsBtdd�|dD��}d|vr"dSd|vr>d|vr>|d|d<dS)Ncss|]}|��VqdSr��rM)r$�ir!r!r&r��r(z'set_krbcanonicalname.<locals>.<genexpr>�objectclassZkrbprincipalaux�krbprincipalname�krbcanonicalname)�set)r�Z
objectclassesr!r!r&�set_krbcanonicalname�s�rYcGsB|�|jddg�}|j�dd�}||dvr>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
    rWrVNrXzHat least one value equal to the canonical principal name must be present�rIr_)�	get_entry�dnr9r�r	�ValidationErrorr)�ldapr��keysr;rWr!r!r&�ensure_last_krbprincipalname�s	
��r`cCsV|�|jgd��}|j�dd�dur(dSt|�|�dd�|�dd�|�|�dS)N)rWrVrUrWrVrU)r[r\r9r�rYr��update)r^r�Z	old_entryr!r!r&�ensure_krbcanonicalname_set�s�rbcCs^d}|durF|jtjkrFtj�|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
    r NTz5IPA client is not configured on this system (confdir z is missing �)z+IPA client is not configured on this system)	ZconfdirrZETC_IPArfrgrhZconf_defaultrr)r3ZCLIENT_NOT_CONFIGUREDr!r!r&�check_client_configuration�s$����rdcCs�|jjddd�d}t�}|D]\}|�dg�}|�tdd�|D���d|vrd|�|dd���|�|d	d���q|r�|�|jj���|S)
z�
    Return UPNs and realm names of trusted forests.

    :param api_instance: API instance
    :param add_local: bool flag

    :return: set of namespace names as strings.
             If add_local is True, add own realm namesapce
    r-r)Z	sizelimitrNZipantadditionalsuffixescss|]}|��VqdSr�rS)r$�upnr!r!r&r��r(z,_collect_trust_namespaces.<locals>.<genexpr>Z
ipantflatnameZcn)	r7Z
trust_findrXr�ra�addrMr3r�)�api_instance�	add_localZ
trust_objects�trust_suffix_namespacer=Znt_suffixesr!r!r&�_collect_trust_namespaces�s
�rjrV)�	attr_namecGsft|dd�}|dD]L}t||jjd�}|j}|jr:|jnd}||vsN||vrtj|td�d��qdS)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
    F�rhrX�r�Nz:realm or UPN suffix overlaps with trusted domain namespacerZ)	rjrr3r��
is_enterprise�
upn_suffixr	r]r)rgrk�suffixesri�p�	principalr�rer!r!r&�(check_principal_realm_in_trust_namespace�s��rsc	Gs~t|dd�}|dD]d}t||jjd�}|j}|jr:|jnd}|��|v|duoZ|��|vg}t|�rtj	|t
d�d��qdS)aJ
    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 does not match with realm name, UPN
    suffix or netbios name of trusted domains or IPA domain
    TrlrXrmNzSrealm or UPN suffix outside of supported realm domains or trusted domains namespacerZ)rjrr3r�rnrorMr�r	r]r)	rgrkrprirqrrr�reZ
conditionsr!r!r&�check_principal_realm_supporteds �

��rtcCs6|D],}|��st�d|�td�|�tjd�qdS)Nz.No network interface matches the IP address %sz7WARNING: No network interface matches the IP address {}rc)Zget_matching_interfacer}r~r:r|�sys�stderr)Z	addr_listr�r!r!r&�,no_matching_interface_for_ip_address_warning,s���rwc
CsLzt�dt�|tjd��dWStttjfyFt	j
�dd�YS0dS)z�
    Get current terminal height

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

    Returns:
        int: Terminal height
    Zhhs1234r�LINES�N)�struct�unpack�fcntlZioctl�termiosZ
TIOCGWINSZrmrnr_rf�environr�)�fdr!r!r&�get_terminal_height:s
��r�cCstj�dd�}t�|�S)zl Get path to a pager

    :return: path to the file if it exists otherwise None
    :rtype: str or None
    ZPAGERZless)rfr~r��shutil�which)�pagerr!r!r&�	get_pagerKsr�cCsBtj|gtjd�}z|j�|�|��Wnty<Yn0dS)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�PIPEr��writeZcommunicaterm)rUr�Z
pager_processr!r!r&�
open_in_pagerUsr�csJeZdZeeeeeee	e
eee
d�hZ�fdd�Zdd�Zdd�Z�ZS)�APIReprNcs>tt|���|j��D] \}}t|t�rt||tj	�qdSr�)
r�r�r��__dict__r2r.r3r�ru�maxsize)r�r)r*rr!r&r�rs
zAPIRepr.__init__cCsdt|�S)zOutput with u'' prefix�u)�repr�r�r,�levelr!r!r&�repr_stryszAPIRepr.repr_strcCs.|turdS||jvr"d�|j�St|�SdS)Nz<type 'unicode'>z<type '{}'>)r8�
builtin_typesr|rr�r�r!r!r&�	repr_type}s

zAPIRepr.repr_type)rrrr4r3r5r8�bytesr1r0r/rX�	frozensetr7r�r�r�r�rr!r!rr&r�js
�r�)FF)FFrE)TFFr�)r�)r�)NFFFr)r)r)r)r)r�)N)N)F)rH)�r@Z
__future__rrZloggingrfr^rSr:rAr*rur�r}r|r�rzr�r�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.admintoolrZipapython.kerberosr�version_info�reprlibZPY3r8r6Z_IPA_CLIENT_SYSRESTOREZ_IPA_DEFAULT_CONFZ	getLoggerrr}r#rCrFrPrVr]rarqrvrxr�Z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�rr	r
rrrrr#r%r&r�r6r8r=r>rMrNrOrPrRrYr`rbrdrjrsrtrwr�r�r��Reprr�r�Zapireprr!r!r!r&�<module>s0 

	5�
^
&�
�
#		�G

�		�
!

!
	
(,4


!
 ��