403Webshell
Server IP : 23.254.227.96  /  Your IP : 216.73.216.7
Web Server : Apache/2.4.62 (Unix) OpenSSL/1.1.1k
System : Linux hwsrv-1277026.hostwindsdns.com 4.18.0-477.13.1.el8_8.x86_64 #1 SMP Tue May 30 14:53:41 EDT 2023 x86_64
User : viralblo ( 1001)
PHP Version : 8.1.31
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /usr/lib/python3.6/site-packages/cloudinit/sources/helpers/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /usr/lib/python3.6/site-packages/cloudinit/sources/helpers/__pycache__/azure.cpython-36.opt-1.pyc
3

��b8��@s@ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddlmZddl
mZddlmZmZddlmZddlmZddlmZmZmZmZmZmZmZdd	lmZdd
l m!Z!ddl"m#Z#ej$e%�Z&dZ'd
Z(dZ)dZ*dZ+dZ,dZ-e!j.dddd�Z/dZ0dd�Z1dd�Z2e1dd��Z3e1dd��Z4dd �e5e!j6d!�d"d#�Z7d$d%�Z8e1e#d&fd'd(��Z9e1d)d*��Z:ed+d,��Z;d-d.�Z<e1ej=d/�d0d1��Z>e5e5e5e?d2�d3d4�Z@Gd5d6�d6�ZAGd7d8�d8eB�ZCGd9d:�d:�ZDGd;d<�d<�ZEGd=d>�d>�ZFGd?d@�d@�ZGe1dGdAdB��ZHe1dHdCdD��ZIdEdF�ZJdS)I�N)�contextmanager)�datetime)�ENOENT)�List�Optional)�ElementTree)�escape)�distros�stages�subp�
temp_utils�
url_helper�util�version)�dhcp)�events)�CFG_BUILTINza8:3f:81:10zboot-telemetryzsystem-infoZ
diagnosticZ
compressedi�z'/run/cloud-init/log_pushed_to_kvp_indexzazure-dsz initialize reporter for azure dsT)�name�descriptionZreporting_enabledz�The VM encountered an error during deployment. Please visit https://aka.ms/linuxprovisioningerror for more information on remediation.cs�fdd�}|S)Nc
s*tj�j�jtd���||�SQRXdS)N)rr�parent)r�ReportEventStack�__name__�azure_ds_reporter)�args�kwargs)�func��/usr/lib/python3.6/azure.py�impl@s

z)azure_ds_telemetry_reporter.<locals>.implr)rrr)rr�azure_ds_telemetry_reporter?srcCs\||krdSd
dd�}|jd�}dj||d�||d�||d�|d|d	g�}||kS)z�
    Azure stores the instance ID with an incorrect byte ordering for the
    first parts. This corrects the byte order such that it is consistent with
    that returned by the metadata service.
    F�cSs(dd�tj|d�D�}|j�dj|�S)NcSsg|]}|�qSrr)�.0Zbyterrr�
<listcomp>Usz<is_byte_swapped.<locals>.swap_bytestring.<locals>.<listcomp>r �)�textwrapZwrap�reverse�join)�s�widthZddrrr�swap_bytestringTsz(is_byte_swapped.<locals>.swap_bytestring�-r���)r )�splitr&)Zprevious_idZ
current_idr)�partsZ
swapped_idrrr�is_byte_swappedKs




r0c2Cs:tj�std��tjd�yttj��ttj��}Wn,t	k
rb}ztd�|�WYdd}~XnXyXt
j
ddddgd	d
�\}}d}|r�d|kr�|jd�d}|s�td
��|t|�d}Wnbt
jk
r�}ztd|�|�WYdd}~Xn2t	k
�r}ztd|�|�WYdd}~XnXy`t
j
dddddgd	d
�\}}d}|�r`d|k�r`|jd�d}|�sntd��|t|�d}Wndt
jk
�r�}ztd|�|�WYdd}~Xn2t	k
�r�}ztd|�|�WYdd}~XnXt
jtddtj|�j�dtj|�j�dtj|�j�dft
j�}t
j|�|S)z[Report timestamps related to kernel initialization and systemd
    activation of cloud-initz1distro not using systemd, skipping boot telemetryzCollecting boot telemetryz*Failed to determine kernel start timestampNz/bin/systemctlZshowz-pZUserspaceTimestampMonotonicT)�capture�=r+z8Failed to parse UserspaceTimestampMonotonic from systemdi@Bz-Failed to get UserspaceTimestampMonotonic: %sz<Failed to parse UserspaceTimestampMonotonic from systemd: %szcloud-init-localZInactiveExitTimestampMonotonicz;Failed to parse InactiveExitTimestampMonotonic from systemdz0Failed to get InactiveExitTimestampMonotonic: %sz?Failed to parse InactiveExitTimestampMonotonic from systemd: %szboot-telemetryz5kernel_start=%s user_start=%s cloudinit_activation=%s�Z)r	Zuses_systemd�RuntimeError�LOG�debug�float�timerZuptime�
ValueErrorrr.ZProcessExecutionErrorr�ReportingEvent�BOOT_EVENT_TYPErZutcfromtimestampZ	isoformat�DEFAULT_EVENT_ORIGIN�report_event)Zkernel_start�e�out�_ZtsmZ
user_startZcloudinit_activation�evtrrr�get_boot_telemetrygsx


rBcCsbtj�}tjtddtj�|d|d|dd|dd|dd|d	ftj�}tj|�|S)
z%Collect and report system informationzsystem informationztcloudinit_version=%s, kernel_version=%s, variant=%s, distro_name=%s, distro_version=%s, flavor=%s, python_version=%s�releaseZvariantZdistrr+r �python)	rZsystem_inforr:�SYSTEMINFO_EVENT_TYPErZversion_stringr<r=)�inforArrr�get_system_info�s




rG)�logger_func)�msg�returncCs6t|�r||�tjtd|tj�}tj|dhd�|S)zReport a diagnostic eventzdiagnostic message�log)�excluded_handler_types)�callablerr:�DIAGNOSTIC_EVENT_TYPEr<r=)rIrHrArrr�report_diagnostic_event�srOcCsPtjtj|��}d|jd�d�}tjt|tj	|�tj
�}tj|dddhd�|S)zReport a compressed eventzgz+b64�ascii)�encoding�datarK�printZwebhook)rL)�base64Zencodebytes�zlib�compress�decoderr:�COMPRESSED_EVENT_TYPE�json�dumpsr<r=)Z
event_nameZ
event_contentZcompressed_dataZ
event_datarArrr�report_compressed_event�sr[Zdef_log_filecCs@t�}tjd�y�t|d��t}|jdtj�t|j�t	|�}t
dj|j�||�tjd�|j|tj�t
d|j��tjtt|j���WdQRXWn8tk
r�}zt
dt|�tjd�WYdd}~XnXtjd	�y$tjd
gddd
�\}}t
d
|�Wn:tk
�r:}zt
dt|�tjd�WYdd}~XnXdS)azPush a portion of cloud-init.log file or the whole file to KVP
    based on the file size.
    The first time this function is called after VM boot, It will push the last
    n bytes of the log file such that n < MAX_LOG_TO_KVP_LENGTH
    If called again on the same boot, it continues from where it left off.
    In addition to cloud-init.log, dmesg log will also be collected.z"Dumping cloud-init.log file to KVP�rbrzMDumping last {0} bytes of cloud-init.log file to KVP starting from index: {1})rHzcloud-init.logNz#Exception when dumping log file: %szDumping dmesg log to KVPZdmesgFT)rWr1z$Exception when dumping dmesg log: %s)�%get_last_log_byte_pushed_to_kvp_indexr5r6�open�seek�os�SEEK_END�max�tell�MAX_LOG_TO_KVP_LENGTHrO�format�SEEK_SETr[�readrZ
write_file�LOG_PUSHED_TO_KVP_INDEX_FILE�str�	Exception�repr�warningr)�	file_nameZstart_index�fZ
seek_index�exr?r@rrr�push_log_to_kvp�s2	

"


rpcCs�y"ttd��}t|j��SQRXWn�tk
rd}z&|jtkrTtdt|�t	j
d�WYdd}~Xnntk
r�}ztdt|�t	j
d�WYdd}~Xn8tk
r�}ztdt|�t	j
d�WYdd}~XnXdS)N�rz0Reading LOG_PUSHED_TO_KVP_INDEX_FILE failed: %s.)rHz2Invalid value in LOG_PUSHED_TO_KVP_INDEX_FILE: %s.z2Failed to get the last log byte pushed to KVP: %s.r)
r^rh�intrg�IOError�errnorrOrkr5rlr9rj)rnr>rrrr]&s"



r]ccs6tj�}tjtjj|��z
dVWdtj|�XdS)N)r`�getcwd�chdir�path�
expanduser)ZnewdirZprevdirrrr�cd>s

rycCstj�rd}nd}|S)Nz
option-245zunknown-245)rZ
is_FreeBSD)Zazure_endpointrrr�_get_dhcp_endpoint_option_nameHsrz)rJc	Ks�d}d}d}d}d|kr ||d<|jdd�r6tjd�|jdd�rLtjd	�x�td
|d
�D]�}y(tj|f|�}td||ftjd�|Stk
r�}z4||d
kr�td|||ftjd�||krȂWYdd}~XnXt	j
|�q\Wtd��dS)zvWrapper around url_helper.readurl() with custom telemetry logging
    that url_helper.readurl() does not provide.
    ����ZtimeoutZretriesNzGIgnoring retries kwarg passed in for communication with Azure endpoint.ZinfinitezHIgnoring infinite kwarg passed in for communication with Azure endpoint.r+z@Successful HTTP request with Azure endpoint %s after %d attempts)rHrzOFailed HTTP request with Azure endpoint %s during attempt %d with exception: %sz%Failed to return in http_with_retries)�popr5rl�ranger
ZreadurlrOr6rjr8�sleepr4)	�urlrZmax_readurl_attemptsZdefault_readurl_timeoutZsleep_duration_between_retriesZperiodic_logging_attemptsZattempt�retr>rrr�http_with_retriesPs<


r�)�username�hostname�
disableSshPwdrJcCs$tjd�}|j|||d�}|jd�S)Na.        <ns0:Environment xmlns:ns0="http://schemas.dmtf.org/ovf/environment/1"
         xmlns:ns1="http://schemas.microsoft.com/windowsazure"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <ns1:ProvisioningSection>
            <ns1:Version>1.0</ns1:Version>
            <ns1:LinuxProvisioningConfigurationSet>
              <ns1:ConfigurationSetType>LinuxProvisioningConfiguration
              </ns1:ConfigurationSetType>
              <ns1:UserName>{username}</ns1:UserName>
              <ns1:DisableSshPasswordAuthentication>{disableSshPwd}
              </ns1:DisableSshPasswordAuthentication>
              <ns1:HostName>{hostname}</ns1:HostName>
            </ns1:LinuxProvisioningConfigurationSet>
          </ns1:ProvisioningSection>
          <ns1:PlatformSettingsSection>
            <ns1:Version>1.0</ns1:Version>
            <ns1:PlatformSettings>
              <ns1:ProvisionGuestAgent>true</ns1:ProvisionGuestAgent>
            </ns1:PlatformSettings>
          </ns1:PlatformSettingsSection>
        </ns0:Environment>
        )r�r�r�zutf-8)r$�dedentre�encode)r�r�r�ZOVF_ENV_TEMPLATEr�rrr�build_minimal_ovf�s
r�c@sBeZdZddd�Zdd�Zd
ejd�dd	�Zdejd�dd�Zd
S)�AzureEndpointHttpClientZWALinuxAgentz
2012-11-30)zx-ms-agent-namezx-ms-versioncCsd|d�|_dS)NZDES_EDE3_CBC)zx-ms-cipher-namez!x-ms-guest-agent-public-x509-cert)�extra_secure_headers)�self�certificaterrr�__init__�sz AzureEndpointHttpClient.__init__F)rJcCs,|j}|r |jj�}|j|j�t||d�S)N)�headers)r��copy�updater�r�)r�r��securer�rrr�get�s

zAzureEndpointHttpClient.getNcCs0|j}|dk	r"|jj�}|j|�t|||d�S)N)rRr�)r�r�r�r�)r�r�rR�
extra_headersr�rrr�post�s


zAzureEndpointHttpClient.post)F)NN)	r�
__module__�__qualname__r�r�r
�UrlResponser�r�rrrrr��sr�c@seZdZdZdS)�InvalidGoalStateXMLExceptionz9Raised when GoalState XML is invalid or has missing data.N)rr�r��__doc__rrrrr��sr�c@s*eZdZdeeedd�dd�Zdd�ZdS)	�	GoalStateTN)�unparsed_xml�azure_endpoint_client�need_certificaterJcCs||_ytj|�|_Wn8tjk
rN}ztd|tjd��WYdd}~XnX|jd�|_	|jd�|_
|jd�|_x8dD]0}t||�dkrzd
|}t|tjd�t
|��qzWd|_|jd�}|dk	o�|�rtjdd
td��.|jj|dd�j|_|jdk�rt
d��WdQRXdS)ahParses a GoalState XML string and returns a GoalState object.

        @param unparsed_xml: string representing a GoalState XML.
        @param azure_endpoint_client: instance of AzureEndpointHttpClient.
        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML string.
        z!Failed to parse GoalState XML: %s)rHNz./Container/ContainerIdz4./Container/RoleInstanceList/RoleInstance/InstanceIdz
./Incarnation�container_id�instance_id�incarnationzMissing %s in GoalState XMLzD./Container/RoleInstanceList/RoleInstance/Configuration/Certificateszget-certificates-xmlzget certificates xml)rrrT)r�z/Azure endpoint returned empty certificates xml.)r�r�r�)r�r�
fromstring�rootZ
ParseErrorrOr5rl�_text_from_xpathr�r�r��getattrr��certificates_xmlrrrr��contents)r�r�r�r�r>�attrrIr�rrrr��s<



zGoalState.__init__cCs|jj|�}|dk	r|jSdS)N)r��find�text)r�Zxpath�elementrrrr�szGoalState._text_from_xpath)T)rr�r�rir��boolr�r�rrrrr��s2r�c@s�eZdZddd�Zdd�Zdd�Zedd	��Zejd
d	��Ze	dd��Z
ee	d
d���Ze	dd��Z
e	dd��Ze	dd��Ze	dd��ZdS)�OpenSSLManagerzTransportPrivate.pemzTransportCert.pem)�private_keyr�cCstj�|_d|_|j�dS)N)rZmkdtemp�tmpdir�_certificate�generate_certificate)r�rrrr�s
zOpenSSLManager.__init__cCstj|j�dS)N)rZdel_dirr�)r�rrr�clean_upszOpenSSLManager.clean_upcCs|jS)N)r�)r�rrrr�szOpenSSLManager.certificatecCs
||_dS)N)r�)r��valuerrrr�scCs�tjd�|jdk	r"tjd�dSt|j��ntjddddddd	d
ddd
|jdd|jdg�d}x*t|jd�D]}d|krt||j�7}qtW||_WdQRXtjd�dS)Nz7Generating certificate for communication with fabric...zCertificate already generated.�opensslZreqz-x509z-nodesz-subjz/CN=LinuxTransportz-daysZ32768z-newkeyzrsa:2048z-keyoutr�z-outr�r#ZCERTIFICATEzNew certificate generated.)	r5r6r�ryr�r�certificate_namesr^�rstrip)r�r��linerrrr�s4


z#OpenSSLManager.generate_certificatecCs"ddd|g}tj||d�\}}|S)Nr�Zx509z-noout)rR)r)�actionZcert�cmd�resultr@rrr�_run_x509_action?szOpenSSLManager._run_x509_actioncCs2|jd|�}ddddddg}tj||d�\}}|S)	Nz-pubkeyz
ssh-keygenz-iz-mZPKCS8z-fz
/dev/stdin)rR)r�r)r�r�Zpub_keyZ
keygen_cmd�ssh_keyr@rrr�_get_ssh_key_from_certFsz%OpenSSLManager._get_ssh_key_from_certcCs6|jd|�}|jd�}||dd�jd�}dj|�S)aopenssl x509 formats fingerprints as so:
        'SHA1 Fingerprint=07:3E:19:D1:4D:1C:79:92:24:C6:A0:FD:8D:DA:        B6:A8:BF:27:D4:73
'

        Azure control plane passes that fingerprint as so:
        '073E19D14D1C799224C6A0FD8DDAB6A8BF27D473'
        z-fingerprintr2r+�:r#���)r�r�r.r&)r�r�Zraw_fp�eqZoctetsrrr�_get_fingerprint_from_certMs	
z)OpenSSLManager._get_fingerprint_from_certcCsjtj|�jd�}|j}ddddd|jd�g}t|j��*tjdjf|j	�d	d
j
|�d�\}}WdQRX|S)
z�Decrypt the certificates XML document using the our private key;
        return the list of certs and private keys contained in the doc.
        z.//DatasMIME-Version: 1.0s<Content-Disposition: attachment; filename="Certificates.p7m"s?Content-Type: application/x-pkcs7-mime; name="Certificates.p7m"s!Content-Transfer-Encoding: base64�zutf-8zuopenssl cms -decrypt -in /dev/stdin -inkey {private_key} -recip {certificate} | openssl pkcs12 -nodes -password pass:T�
)�shellrRN)rr�r�r�r�ryr�rrer�r&)r�r��tagZcertificates_content�linesr?r@rrr�_decrypt_certs_from_xml[sz&OpenSSLManager._decrypt_certs_from_xmlc	Csz|j|�}g}i}xb|j�D]V}|j|�tjd|�r<g}qtjd|�rdj|�}|j|�}|j|�}|||<g}qW|S)z�Given the Certificates XML document, return a dictionary of
        fingerprints and associated SSH keys derived from the certs.z[-]+END .*?KEY[-]+$z[-]+END .*?CERTIFICATE[-]+$�
)r��
splitlines�append�re�matchr&r�r�)	r�r�r?Zcurrent�keysr�r�r��fingerprintrrr�parse_certificatests




z!OpenSSLManager.parse_certificatesN)rr�r�r�r�r��propertyr��setterrr��staticmethodr�r�r�r�r�rrrrr�s r�c@s�eZdZejd�Zejd�ZdZdZdZ	dZ
eee
dd�d	d
�Zedd�dd
��Zee
dd�dd��Zde
e
e
e
e
d�dd�Zee
dd�dd��ZdS)�GoalStateHealthReportera�        <?xml version="1.0" encoding="utf-8"?>
        <Health xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <GoalStateIncarnation>{incarnation}</GoalStateIncarnation>
          <Container>
            <ContainerId>{container_id}</ContainerId>
            <RoleInstanceList>
              <Role>
                <InstanceId>{instance_id}</InstanceId>
                <Health>
                  <State>{health_status}</State>
                  {health_detail_subsection}
                </Health>
              </Role>
            </RoleInstanceList>
          </Container>
        </Health>
        z�        <Details>
          <SubStatus>{health_substatus}</SubStatus>
          <Description>{health_description}</Description>
        </Details>
        ZReadyZNotReadyZProvisioningFailediN)�
goal_stater��endpointrJcCs||_||_||_dS)a?Creates instance that will report provisioning status to an endpoint

        @param goal_state: An instance of class GoalState that contains
            goal state info such as incarnation, container id, and instance id.
            These 3 values are needed when reporting the provisioning status
            to Azure
        @param azure_endpoint_client: Instance of class AzureEndpointHttpClient
        @param endpoint: Endpoint (string) where the provisioning status report
            will be sent to
        @return: Instance of class GoalStateHealthReporter
        N)�_goal_state�_azure_endpoint_client�	_endpoint)r�r�r�r�rrrr��sz GoalStateHealthReporter.__init__)rJcCs�|j|jj|jj|jj|jd�}tjd�y|j|d�Wn6t	k
rp}zt
d|tjd��WYdd}~XnXtjd�dS)N)r�r�r��statusz Reporting ready to Azure fabric.)�documentz#exception while reporting ready: %s)rHzReported ready to Azure fabric.)
�build_reportr�r�r�r��PROVISIONING_SUCCESS_STATUSr5r6�_post_health_reportrjrO�errorrF)r�r�r>rrr�send_ready_signal�s


z)GoalStateHealthReporter.send_ready_signal)rrJcCs�|j|jj|jj|jj|j|j|d�}y|j|d�Wn:tk
rp}zd|}t	|t
jd��WYdd}~XnXt
jd�dS)N)r�r�r�r��	substatusr)r�z%exception while reporting failure: %s)rHz!Reported failure to Azure fabric.)
r�r�r�r�r��PROVISIONING_NOT_READY_STATUS�PROVISIONING_FAILURE_SUBSTATUSr�rjrOr5r�rl)r�rr�r>rIrrr�send_failure_signal�sz+GoalStateHealthReporter.send_failure_signal)r�r�r�r�rJc	Cs\d}|dk	r.|jjt|�t|d|j��d�}|jjtt|��t|�t|�t|�|d�}|S)Nr#)Zhealth_substatusZhealth_description)r�r�r�Z
health_statusZhealth_detail_subsection)�%HEALTH_DETAIL_SUBSECTION_XML_TEMPLATErer�"HEALTH_REPORT_DESCRIPTION_TRIM_LEN�HEALTH_REPORT_XML_TEMPLATEri)	r�r�r�r�r�r�rZ
health_detailZ
health_reportrrrr��s	
z$GoalStateHealthReporter.build_report)r�rJcCsJt�tjd�tjd�dj|j�}|jj||ddid�tjd�dS)Nrz&Sending health report to Azure fabric.zhttp://{}/machine?comp=healthzContent-Typeztext/xml; charset=utf-8)rRr�z/Successfully sent health report to Azure fabric)	rpr8r�r5r6rer�r�r�)r�r�r�rrrr�s

z+GoalStateHealthReporter._post_health_report)NN)rr�r�r$r�r�r�r�r�r�r�r�r�rir�rr�r�r�r�rrrrr��s*
r�c@s@eZdZd,dd�Zdd�Zedd��Zedd	��Zed
d��Z	ee
d-dd
���Zee
dd���Zee
dd���Z
ee
dd���Zee
d.dd���Ze
dd�dd��Ze
d/eeed�dd��Ze
edd�dd��Ze
eed�dd ��Ze
ed�d!d"��Ze
eeed#�d$d%��Ze
eeed&�d'd(��Zeeeed)�d*d+��ZdS)0�WALinuxAgentShimNcCs.tjd|�||_d|_d|_d|_||_dS)Nz5WALinuxAgentShim instantiated, fallback_lease_file=%s)r5r6�dhcpoptionsr��openssl_managerr��
lease_file)r��fallback_lease_file�dhcp_optionsrrrr�+szWALinuxAgentShim.__init__cCs|jdk	r|jj�dS)N)r�r�)r�rrrr�6s
zWALinuxAgentShim.clean_upcCstj�}tjj|jj�d�S)Nzdhclient.hooks)r
ZInitr`rwr&�pathsZget_runpath)Z_pathsrrr�_get_hooks_dir:szWALinuxAgentShim._get_hooks_dircCs"|jdkr|j|j|j�|_|jS)N)r��
find_endpointr�r�)r�rrrr�?s
zWALinuxAgentShim.endpointcCs||jdd�}t|�dkrhd}x.|jd�D] }t|�dkr@d|}||7}q(Wtjdt|jdd�d��}n
|jd	�}tj|�S)
N�\r#r-r�r+�0z>L�zutf-8)	�replace�lenr.�struct�packrrr��socketZ	inet_ntoa)Zfallback_lease_valueZunescaped_valueZ
hex_stringZhex_pairZpacked_bytesrrr�get_ip_from_lease_valueGs
z(WALinuxAgentShim.get_ip_from_lease_valuecCstjd|d�S)NZ
OPTION_245)�leases_d)rZnetworkd_get_option_from_leases)r�rrr�_networkd_get_value_from_leasesWsz0WALinuxAgentShim._networkd_get_value_from_leasescCs�g}ytj|�}Wn.tk
r@}ztjd||�dSd}~XnXtjd|�t�}x:|j�D].}||kr^|j|j	d�j
dd�dj	d��q^Wt|�dkr�dS|dSdS)	NzFailed to read %s: %sz
content is %s� r r+z;
"r�r�)r�	load_filersr5r�r6rzr�r��stripr.r�)r�ZleasesZcontentroZoption_namer�rrr�_get_value_from_leases_file^s&z,WALinuxAgentShim._get_value_from_leases_filecs�i}tj��tjj��s(tjd��dS�fdd�tj��D�}xn|D]f}y,tjj|�j	dd�}t
jtj
|��||<WqFtk
r�}ztdj|d��|�WYdd}~XqFXqFW|S)Nz
%s not found.csg|]}tjj�|��qSr)r`rwr&)r!�x)�	hooks_dirrrr"~sz8WALinuxAgentShim._load_dhclient_json.<locals>.<listcomp>z.jsonr#z{_file} is not valid JSON data)Z_file)r�r�r`rw�existsr5r6�listdir�basenamer�rY�loadsrr�r9re)r�Z
hook_filesZ	hook_filerr>r)rr�_load_dhclient_jsonus
z$WALinuxAgentShim._load_dhclient_jsoncCsF|dkrdSd}x0|D](}||jdd�}|dk	rtjd�PqW|S)NZunknown_245z)Endpoint server found in dhclient options)r�r5r6)r�Z_valueZ	interfacerrr�_get_value_from_dhcpoptions�s

z,WALinuxAgentShim._get_value_from_dhcpoptionscCs�d}|dk	r|}tjd�|dkr8tdtjd�tj�}|dkr`tdtjd�tj�}tj|�}|dkr�tdtjd�|dkr�tdtjd�d}ntd|tjd�tj|�}|dkr�t	}td	|tjd�tj
|�}td
|tjd�|S)aLFinds and returns the Azure endpoint using various methods.

        The Azure endpoint is searched in the following order:
        1. Endpoint from dhcp options (dhcp option 245).
        2. Endpoint from networkd.
        3. Endpoint from dhclient hook json.
        4. Endpoint from fallback lease file.
        5. The default Azure endpoint.

        @param fallback_lease_file: Fallback lease file that will be used
            during endpoint search.
        @param dhcp245: dhcp options that will be used during endpoint search.
        @return: Azure endpoint IP address.
        Nz&Using Azure Endpoint from dhcp optionszLNo Azure endpoint from dhcp options. Finding Azure endpoint from networkd...)rHzINo Azure endpoint from networkd. Finding Azure endpoint from hook json...zqNo Azure endpoint from dhclient logs. Unable to find endpoint in dhclient logs. Falling back to check lease filesz%No fallback lease file was specified.z%Looking for endpoint in lease file %sz*No lease found; using default endpoint: %szAzure endpoint found at %s)r5r6rOr�r�rrrlr��DEFAULT_WIRESERVER_ENDPOINTr�)r�Zdhcp245r�r�Zendpoint_ip_addressrrrr��sP









zWALinuxAgentShim.find_endpoint)rJcCsVytjd�tjd|g�Wn4tk
rP}ztd|tjd�WYdd}~XnXdS)NzEjecting the provisioning isoZejectz(Failed ejecting the provisioning iso: %s)rH)r5r6rrjrO)r��iso_devr>rrr�	eject_iso�s
zWALinuxAgentShim.eject_isocCs�d}|jdkr&|dk	r&t�|_|jj}|jdkr:t|�|_|j|dk	d�}d}|dk	rb|j||�}t||j|j�}|dk	r�|j	|�|j
�|S)a�Gets the VM's GoalState from Azure, uses the GoalState information
        to report ready/send the ready signal/provisioning complete signal to
        Azure, and then uses pubkey_info to filter and obtain the user's
        pubkeys from the GoalState.

        @param pubkey_info: List of pubkey values and fingerprints which are
            used to filter and obtain the user's pubkey values from the
            GoalState.
        @return: The list of user's authorized pubkey values.
        N)r�)r�r�r�r�r��_fetch_goal_state_from_azure�_get_user_pubkeysr�r�r	r�)r��pubkey_inforZhttp_client_certificater��ssh_keys�health_reporterrrr�"register_with_azure_and_fetch_data�s$

z3WALinuxAgentShim.register_with_azure_and_fetch_data)rrJcCs@|jdkrtd�|_|jdd�}t||j|j�}|j|d�dS)z�Gets the VM's GoalState from Azure, uses the GoalState information
        to report failure/send provisioning failure signal to Azure.

        @param: user visible error description of provisioning failure.
        NF)r�)r)r�r�r
r�r�r�)r�rr�rrrr�&register_with_azure_and_report_failures

z7WALinuxAgentShim.register_with_azure_and_report_failure)r�rJcCs|j�}|j||�S)aFetches the GoalState XML from the Azure endpoint, parses the XML,
        and returns a GoalState object.

        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML
        )�"_get_raw_goal_state_xml_from_azure�_parse_raw_goal_state_xml)r�r��unparsed_goal_state_xmlrrrr
$s
z-WALinuxAgentShim._fetch_goal_state_from_azurecCs�tjd�dj|j�}y,tjddtd��|jj|�}WdQRXWn6t	k
rx}zt
d|tjd��WYdd}~XnXtjd	�|j
S)
z�Fetches the GoalState XML from the Azure endpoint and returns
        the XML as a string.

        @return: GoalState XML string
        zRegistering with Azure...z!http://{}/machine/?comp=goalstatezgoalstate-retrievalzretrieve goalstate)rrrNz9failed to register with Azure and fetch GoalState XML: %s)rHz#Successfully fetched GoalState XML.)r5rFrer�rrrr�r�rjrOrlr6r�)r�r�Zresponser>rrrr3s 



z3WALinuxAgentShim._get_raw_goal_state_xml_from_azure)rr�rJcCs~yt||j|�}Wn6tk
rH}ztd|tjd��WYdd}~XnXdjd|jd|jd|j	g�}t|tj
d�|S)aParses a GoalState XML string and returns a GoalState object.

        @param unparsed_goal_state_xml: GoalState XML string
        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML
        z"Error processing GoalState XML: %s)rHNz, zGoalState XML container id: %szGoalState XML instance id: %szGoalState XML incarnation: %s)r�r�rjrOr5rlr&r�r�r�r6)r�rr�r�r>rIrrrrNs 


z*WALinuxAgentShim._parse_raw_goal_state_xml)r�rrJcCs>g}|jdk	r:|dk	r:tjd�|jj|j�}|j||�}|S)a�Gets and filters the VM admin user's authorized pubkeys.

        The admin user in this case is the username specified as "admin"
        when deploying VMs on Azure.
        See https://docs.microsoft.com/en-us/cli/azure/vm#az-vm-create.
        cloud-init expects a straightforward array of keys to be dropped
        into the admin user's authorized_keys file. Azure control plane exposes
        multiple public keys to the VM via wireserver. Select just the
        admin user's key(s) and return them, ignoring any other certs.

        @param goal_state: GoalState object. The GoalState object contains
            a certificate XML, which contains both the VM user's authorized
            pubkeys and other non-user pubkeys, which are used for
            MSI and protected extension handling.
        @param pubkey_info: List of VM user pubkey dicts that were previously
            obtained from provisioning data.
            Each pubkey dict in this list can either have the format
            pubkey['value'] or pubkey['fingerprint'].
            Each pubkey['fingerprint'] in the list is used to filter
            and obtain the actual pubkey value from the GoalState
            certificates XML.
            Each pubkey['value'] requires no further processing and is
            immediately added to the return list.
        @return: A list of the VM user's authorized pubkey values.
        Nz/Certificate XML found; parsing out public keys.)r�r5r6r�r��_filter_pubkeys)r�r�rr
�keys_by_fingerprintrrrrns
z"WALinuxAgentShim._get_user_pubkeys)rrrJcCs�g}xv|D]n}d|kr.|dr.|j|d�q
d|krl|drl|d}||kr^|j||�qxtjd|�q
tjd|�q
W|S)a8Filter and return only the user's actual pubkeys.

        @param keys_by_fingerprint: pubkey fingerprint -> pubkey value dict
            that was obtained from GoalState Certificates XML. May contain
            non-user pubkeys.
        @param pubkey_info: List of VM user pubkeys. Pubkey values are added
            to the return list without further processing. Pubkey fingerprints
            are used to filter and obtain the actual pubkey values from
            keys_by_fingerprint.
        @return: A list of the VM user's authorized pubkey values.
        r�r�zIovf-env.xml specified PublicKey fingerprint %s not found in goalstate XMLzFovf-env.xml specified PublicKey with neither value nor fingerprint: %s)r�r5rl)rrr�Zpubkeyr�rrrr�s


z WALinuxAgentShim._filter_pubkeys)NN)N)NN)NN)rr�r�r�r�r�r�r�r�r�rr�r�rrr�r	rrrirrr�r�r
rr�listr�dictrrrrrr�*sJ

J
##r�c
Cs*t||d�}z|j||d�S|j�XdS)N)r�r�)rr)r�rr�)r��	dhcp_optsrr�shimrrr�get_metadata_from_fabric�s

rc
Cs4t||d�}|st}z|j|d�Wd|j�XdS)N)r�r�)r)r��+DEFAULT_REPORT_FAILURE_USER_VISIBLE_MESSAGErr�)r�rrrrrr�report_failure_to_fabric�s
rcCs(td|tjd�td|tjd�dS)Nzdhclient output stream: %s)rHzdhclient error stream: %s)rOr5r6)r?�errrrr�dhcp_log_cb�sr)NNNN)NNN)KrTrYZloggingr`r�r�r�r$r8rU�
contextlibrrrtrZtypingrrZ	xml.etreerZxml.sax.saxutilsrZ	cloudinitr	r
rrr
rrZ
cloudinit.netrZcloudinit.reportingrZcloudinit.settingsrZ	getLoggerrr5rr;rErNrXrdrhrrrrr0rBrGrir:rOr[rpr]ryrzr�r��bytesr�r�rjr�r�r�r�r�rrrrrrr�<module>s�$	
T(
5 ?"


Youez - 2016 - github.com/yon3zu
LinuXploit