
    A                     "   S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKJr  SSK	J
r
  SSK	Jr  SS	K	Jr  SS
K	Jr  SSK	Jr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr   SSK	Jr  Sr!Sr"Sr#Sr$SS/r%Sr&\RN                  " S5      r(\RN                  " S5      r)\RN                  " S5      r*\RN                  " S5      r+\RN                  " S 5      r,\RN                  " S!5      r-\RN                  " S"5      r.\R^                  \R`                  " \Rb                  Rd                  \Rb                  Rf                  \Rb                  Rh                  5       " S# S$\Rj                  5      5       5       r6g! \  a    Sr GNf = f)%zFImplements the command for resetting a password in a Windows instance.    )absolute_import)division)unicode_literalsN)encoding)base_classes)	constants)metadata_utils)openssl_encryption_utils)utils)base)flags)gaia)	time_util)log)
properties)
console_io)files)windows_encryption_utilsz%Y-%m-%dT%H:%M:%S+0000   i,  zwindows-keyszgce-initial-windows-userzgce-initial-windows-password   z    Did not receive password in a reasonable amount of time. Please try again.
    If this persists, confirm that the clock on your local system is correct.
    Current UTC time on your system: [{0}]z
    The instance may not be ready for use. This can occur if the instance was
    recently created or if the instance is not running Windows.
    Please wait a few minutes and try again.a,  
    This Windows instance appears to be too old and does not support the
    reset-windows-password command. Please run the following command and look
    for the keys "gce-initial-windows-user" and "gce-initial-windows-password"
    in the metadata:
      [gcloud compute instances describe {0} --zone {1}]
    Alternatively, you can recreate the instance and update it to take
    advantage of reset-windows-password. More information can be found here:
    https://cloud.google.com/compute/docs/operating-systems/windows#upgrade_existing_instances
    z
    User [{0}] cannot be created on instance [{1}].
    The user name and instance name must differ on Windows instances.
    Please use the "--user" flag to select a different username for this
    instance.z    Instance [{0}] does not appear to have an external IP
    address, so it will not be able to accept external connections.
    To add an external IP address to the instance, use
    gcloud compute instances add-access-config.a      Instance [{0}] appears to have been created with an older
    version of gcloud (or another tool that is still setting legacy credentials
    for Windows instances) and the metadata for this instance contains insecure
    (and likely invalid) authentication credentials. It is recommended that
    they be removed with the following command:
    [gcloud compute instances remove-metadata {1} --zone {2} --keys {3}]
    a  
    This command creates an account and sets an initial password for the
    user [{0}] if the account does not already exist.
    If the account already exists, resetting the password can cause the
    LOSS OF ENCRYPTED DATA secured with the current password, including
    files and stored passwords.

    For more information, see:
    https://cloud.google.com/compute/docs/operating-systems/windows#resetc                   z    \ rS rSrSr\R                  r\S 5       r	S r
S rS rS rS rS	 rSS
 jrS rS rSrg)ResetWindowsPasswordl   a  Reset and return a password for a Windows machine instance.

*{command}* allows a user to reset and retrieve a password for
a Windows virtual machine instance. If the Windows account does not
exist, this command will cause the account to be created and the
password for that new account will be returned.

For Windows instances that are running a domain controller, running
this command creates a new domain user if the user does not exist,
or resets the password if the user does exist. It is not possible to
use this command to create a local user on a domain-controller
instance.

NOTE: When resetting passwords or adding a new user to a Domain Controller
in this way, the user will be added to the built in Admin Group on the
Domain Controller. This will give the user wide reaching permissions. If
this is not the desired outcome then Active Directory Users and Computers
should be used instead.

For all other instances, including domain-joined instances, running
this command creates a local user or resets the password for a local
user.

WARNING: Resetting a password for an existing user can cause the
loss of data encrypted with the current Windows password, such as
encrypted files or stored passwords.

The user running this command must have write permission for the
Google Compute Engine project containing the Windows instance.

## EXAMPLES

To reset the password for user 'foo' on a Windows instance 'my-instance' in
zone 'us-central1-f', run:

  $ {command} my-instance --zone=us-central1-f --user=foo
c                     U R                   R                  S5        U R                  SSS9  [        R                  R                  U 5        g )Nz[private]textz--userz        ``USER'' specifies the username to get the password for.
        If omitted, the username is derived from your authenticated
        account email address.
        )help)display_info	AddFormatadd_argumentinstance_flagsINSTANCE_ARGAddArgument)parsers    -lib/surface/compute/reset_windows_password.pyArgsResetWindowsPassword.Args   sG    
!!/2
   ++F3    c                     UR                   R                  SUR                  R                  " S0 UR	                  5       D64$ )NGet )apitools_client	instancesmessagesComputeInstancesGetRequestAsDict)selfclientinstance_refs      r#   GetGetRequest"ResetWindowsPassword.GetGetRequest   s>    "",,OO66O9L9L9NOQ Qr&   c                     UR                   R                  SUR                  R                  " SSUR                  0UR                  5       D64$ )NSetMetadatametadatar)   )r*   r+   r,   "ComputeInstancesSetMetadataRequestr6   r.   )r/   r0   r1   replacements       r#   GetSetRequest"ResetWindowsPassword.GetSetRequest   sO    "",,OO>> )$--)%%')* *r&   c                 f    [         R                  R                  X2[         R                  " U5      S9$ )N)scope_lister)r   r    ResolveAsResourceGetInstanceZoneScopeLister)r/   r0   	resourcesargss       r#   CreateReference$ResetWindowsPassword.CreateReference   s3    &&88#>>vF 9 H Hr&   c                     [         R                  " U5      n[        USS 5      n[        R                  " UR
                  [        U R                  U5      0US9nXSl        U$ )Nr6   )message_classesr6   existing_metadata)	r   CopyProtoMessagegetattrr	   ConstructMetadataMessager,   METADATA_KEY_UpdateWindowsKeysValuer6   )r/   r0   existing
new_objectrE   new_metadatas         r#   ModifyResetWindowsPassword.Modify   sb    **84J*d;!::(():;= ,-L 'r&   c                     [         R                  " [        5      nU[        R                  " U5      [        R                  " U5      UUS.n[
        R                  " USS9nU$ )z1Return a JSON formatted entry for 'windows-keys'.)userNamemodulusexponentemailexpireOnT)	sort_keys)r   CalculateExpirationRSA_KEY_EXPIRATION_TIME_SECcore_encodingDecodejsondumps)r/   userrR   rS   rT   
expire_strwindows_key_datawindows_key_entrys           r#   _ConstructWindowsKeyEntry.ResetWindowsPassword._ConstructWindowsKeyEntry   sZ    ../JKJ$(#0#7#7#@$1$8$8$B!&$.	0 

#3tDr&   c                 <   / n/ U l         UR                   H  nUR                  [        :X  aA  UR                  R                  S5       Vs/ s H  oD(       d  M  UR                  5       PM     nnUR                  [        ;   d  Mn  U R                   R                  UR                  5        M     UR                  U R                  5        / nSn[        U5       H  n[        US-   5      nSn [        R                  " U5      n	[        R                  " U	S   5      (       a  SnU(       a'  [$        R&                  " SR)                  U5      5        Mx  Xg-   [*        R,                  :  a6  [$        R&                  " SR)                  [*        R,                  U5      5        M  UR                  U5        Xg-  nM     [$        R&                  " SR)                  [        U5      5      5        UR/                  5         SR1                  U5      $ s  snf ! [         ["        4 a     Nf = f)	ah  Returns a string appropriate for the metadata.

Values are removed if they have expired and non-expired keys are removed
from the head of the list only if the total key size is greater than
MAX_METADATA_VALUE_SIZE_IN_BYTES.

Args:
  existing_metadata: The existing metadata for the instance to be updated.

Returns:
  A new-line-joined string of Windows keys.

r   FrU   TzPThe following Windows key has expired and will be removed from your project: {0}zThe following Windows key will be removed from your project because your windows keys metadata value has reached its maximum allowed size of {0} bytes: {1}zNumber of Windows Keys: {0})old_metadata_keysitemskeyrI   valuesplitstripOLD_METADATA_KEYSappendr`   reversedlenr[   loadsr   	IsExpired
ValueErrorKeyErrorr   debugformatr    MAX_METADATA_VALUE_SIZE_IN_BYTESreversejoin)
r/   rE   windows_keysitemrg   keysbytes_consumed	num_byteskey_expiredkey_datas
             r#   rJ   ,ResetWindowsPassword._UpdateWindowsKeysValue   s    LD!''	\	!/3zz/?/?/EM/E		/EM	&	&%%dhh/	 ( ../ DN%cDj/ik::c?x
344+ 
		 ++16#;	8&889		 ; 6)DDcJ	L
 	C#3 &6 II+223t9=>LLN99T?Q N, (# s   

HH+6HHHc                     UR                   R                  SUR                  R                  " SSU0UR	                  5       D64nUR                  U/5      nUS   R                  $ )z5Returns the serial port output for self.instance_ref.GetSerialPortOutputportr   r)   )r*   r+   r,   *ComputeInstancesGetSerialPortOutputRequestr.   MakeRequestscontents)r/   r0   r1   r   requestobjectss         r#   _GetSerialPortOutput)ResetWindowsPassword._GetSerialPortOutput  sj    %%//$II ,,!((*,-G
 !!7),G1:r&   c                 :   0 n[         R                  " 5       nSnSnU(       Gd  [        R                  " SR	                  U5      5        [         R                  " 5       U[
        -   :  a<  [        R                  " [        R	                  [         R                  " 5       5      5      eU R                  XSS9R                  S5      n[        U5       H  n	 [        R                  " U	5      n
U
R!                  S5      nU(       d  U
R!                  S5      (       a  S	nU
R!                  S
5      (       d  Mb  ["        R$                  " U5      ["        R$                  " U5      :X  d  M  U
n  O   U(       dm  U R&                  (       a@  [(        R	                  UR*                  UR,                  5      n[        R.                  " U5      e[0        n[        R2                  " U5      e[         R4                  " [6        5        US-  nU(       d  GM  US
   nU$ ! [         a     GMJ  f = f)z@Returns the decrypted password from the data in the serial port.   FzGet Serial Port Output, Try {0}   )r   rd   rR   readyTencryptedPassword)r   CurrentTimeSecr   rs   rt   WINDOWS_PASSWORD_TIMEOUT_SECr   TimeoutErrorTIMEOUT_ERRORCurrentDatetimeUtcr   ri   rm   r[   ro   rq   getrY   rZ   re   OLD_WINDOWS_BUILD_ERRORinstancezoneWrongInstanceTypeErrorNOT_READY_ERRORInstanceNotReadyErrorSleepPOLLING_SEC)r/   r0   r1   search_modulusencrypted_password_data
start_timecountagent_readyserial_port_outputlineencrypted_password_dictrR   messageencrypted_passwords                 r#   #_GetEncryptedPasswordFromSerialPort8ResetWindowsPassword._GetEncryptedPasswordFromSerialPort  s    !))+JEK%	ii188?@

"
"
$668    !=!=!?@B 	B44
Q 5 ((-d -.$	$(JJt$4
!
 *--i8-11'::+ '**+>??
  0M4H4H5 $;
!
% /& !!+22<3H3H3?3D3DF',,W5
5#'++G4
4ook"qjeI &%J 11DE5  	
	s   H
HHc           
         [         R                  " U R                  5       5      nUR                  n[        R
                  " 5       n[        R                  " S5      n[        (       a  [        R                  " 5       nO4U(       a  [        R                  " U5      nO[        R                  " S5      e[        R                  R                   R"                  R%                  5       nUR&                  (       a  UR&                  nO[(        R*                  " U5      nUR,                  U:X  a3  [        R.                  " [0        R3                  XR,                  5      5      e[4        R3                  U5      n	SR3                  U5      n
[6        R8                  " U	U
SS9  [:        R<                  R?                  SR3                  XR,                  5      5        URA                  5       nURC                  URE                  U5      5      u  pU RG                  XX5      U l$        U RK                  X2RL                  U5      nU RO                  X>5      nURQ                  U/5      nU RS                  UUS   5      nUS   U:X  a=  [:        R<                  R?                  SR3                  US   RT                  5      5        U$ URQ                  U RW                  X>U5      /5      S   nU RY                  X>U5      nUR[                  UU5      n[]        U[^        5      (       d  [`        Rb                  " U5      n URd                  S   Rf                  nUS   Rh                  nU Rr                  (       ac  [:        Rn                  " [t        R3                  URv                  URv                  URx                  S	R{                  U Rr                  5      5      5        [:        R|                  " S
R3                  [        R
                  " 5       U-
  5      5        UUUS.nU$ ! [j        [l        4 a@  n[:        Rn                  " [p        R3                  URT                  5      5        S n S nAGNS nAff = f)Nopensslz'Your platform does not support OpenSSL.z5Would you like to set or reset the password for [{0}]T)r   prompt_stringcancel_on_noz4Resetting and retrieving password for [{0}] on [{1}]r   z/No change requested; skipping update for [{0}].,zTotal Elapsed Time: {0})usernamepassword
ip_address)?r   ComputeApiHolderReleaseTrackr0   r   r   r   FindExecutableOnPathr   WinCryptr
   OpensslCryptr   MissingDependencyErrorr   VALUEScoreaccount	GetOrFailr]   r    MapGaiaEmailToDefaultAccountNameinstance_nameInvalidUserErrorMACHINE_USERNAME_SAME_ERRORrt   RESET_PASSWORD_WARNINGr   PromptContinuer   statusPrint
GetKeyPairGetModulusExponentFromPublicKeyGetPublicKeyra   r`   rA   r?   r2   r   rN   namer9   r   DecryptMessage
isinstancestrrY   rZ   networkInterfacesaccessConfigsnatIPrr   
IndexErrorwarningNO_IP_WARNINGre   OLD_KEYS_WARNINGr   r   rw   info)r/   r@   holderr0   startopenssl_executablecryptrT   r]   r   r   rg   rR   rS   r1   get_requestr   rL   updated_instanceenc_passwordr   access_configsexternal_ip_address_connection_infos                            r#   RunResetWindowsPassword.RunF  s   **4+<+<+>?F]]F$$&E 33I>&//1e	&334FGe((
35 5 ""**446EyyYYd2259dT!""
%
,
,T3E3E
FH H %++D1GLfTl #
 JJKfT#5#568 


C==3!G ";;x(D
 ''0@0@$GL$$V:K!!;-0GVWQZ0J
 qzZ	jj
;
B
Bajoo  n**			F*	=>@@AC ;;g'L##C6Hh$$%%h/h!'99!<JJn*1-33 	kk")),*?*?*6*?*?*6*;*;*-((43I3I*JL M
 HH&fY--/%78: $(#+%8:O % j! !	kk-&&'7'<'<=> !s   &(P Q5QQ)re   r`   N)r   )__name__
__module____qualname____firstlineno____doc__r   TOOLS_CATEGORYcategorystaticmethodr$   r2   r9   rA   rN   ra   rJ   r   r   r   __static_attributes__r)   r&   r#   r   r   l   sY    $L   (
4 
4Q
*H

:x-^ar&   r   )7r   
__future__r   r   r   r[   textwrapapitools.base.pyr   googlecloudsdk.api_lib.computer   r   r	   r
   r   googlecloudsdk.callioper   ,googlecloudsdk.command_lib.compute.instancesr   r   googlecloudsdk.command_lib.utilr   r   googlecloudsdk.corer   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilrY   r   r   ImportErrorEXPIRATION_DATE_FORMATr   rX   rI   rk   r   dedentr   r   r   r   r   r   r   DefaultUniverseOnlyReleaseTracksr   GABETAALPHAUpdateCommandr   r)   r&   r#   <module>r      s   M &  '   % 7 4 9 C 0 ( P 0 5 # * 2 > *"E 2 ! ! /1OP  !. /
 // #0 1
 #// 	+ 		  'oo /    !3 4 ?? $ 	  " *M N  D%%(($*;*;*@*@%%++-x4-- x- xE  "!"s   8F FF