
    gy                     8   S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SKJ	r
  S SKJrJ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JrJr  S SKJr  S SKJrJrJr  S S	KJ r   S S
K!J"r"J#r#  S SK$J%r%J&r&J'r'  S SKJ(r(  S SK)J*r*  S SK+J,r,J-r-  S SK.J/r/  S SK0J1r1  S SK+J2r2  S SK3J4r4  S SK5r5S SK+J6r6J7r7J8r8  S SK9J:r:J;r;J<r<  S SK=J>r>  S SK?J@r@  S SKArAS SKBJCrC  S SKJDrD  S SKEJFrF  S SKGJHrH  S SKIJJrJ  S SKJKrL  S SKMrMS rNS rOS rPS  rQS! rRS" rS S1S# jrTS$ rUS% rVS& rW " S' S(\R                  R                  5      rZ " S) S*\*5      r[ " S+ S,\R                  R                  5      r\ " S- S.\R                  R                  5      r] " S/ S0\R                  R                  5      r_g)2    N)SamDBget_default_backend_store)LdbError)libsmb_samba_internal)param)backup_onlinebackup_restorebackup_offline)system_session)DCJoinContext
join_cloneDCCloneAndRenameContext)dom_sid)OptionCommandError)miscsecuritydrsblobs)Ldb)cmd_fsmo_seize)make_smbconfDEFAULTSITE)update_krbtgt_account_password)	remove_dc)secretsdb_self_join)dbcheck)guess_namesdetermine_host_ipdetermine_host_ip6)fill_dns_data_partitionsget_dnsadmins_sidget_domainguid)tdb_copy)mdb_copy)CalledProcessError)sites)_dsdb_load_udv_v2)ndr_pack)SMB_SIGNING_REQUIRED)safe_tarfilec                     U R                  5       n[	        U R                  5       5      n[        U5      S-   [        U5      -   n U R                  [        R                  SU-  / SS/S9n[        U5      S	:w  a  [        S
U-  5      e[        SU< SUS   R                  < S35      e! [         a3  nUR                  S5        UR                  S5        [        SU5      eS nAff = f! [        R                   a-  nUR                  u  pU[        R                  :w  a  e  S nAOS nAff = f[        U5      S-   [        U5      -   $ )Nz}A SID could not be allocated for restoring the domain. Either no RID Set was found on this DC, or the RID Set was not usable.zTo initialise this DC's RID pools, obtain a RID Set from this domain's RID master, or run samba-tool dbcheck to fix the existing RID Set.zCannot create backup-<SID=%s>show_deleted:1zshow_recycled:1)scopebaseattrscontrols   z]Cannot create backup - this DC's RID pool is corrupt, the next SID (%s) appears to be in use.zCCannot create backup - this DC's RID pool is corrupt, the next SID z points to existing object r   z1. Please run samba-tool dbcheck on the source DC.)next_free_ridr   infor   r   get_domain_sidstrsearchldb
SCOPE_BASElendnargsERR_NO_SUCH_OBJECT)
samdbloggerriderrsidsid_for_restorereseenumemsgs
             </usr/lib/python3/dist-packages/samba/netcmd/domain/backup.pyget_sid_for_restorerJ   A   sV   	8!!# %&&(
)C#hns3x/Oll *_ <!#%5%6%8  9
 s8q=  I  / / 0 0  ,SVYY	8 9 	95  8 5 	6 	 3 	4 13778> << vv3))) * s8c>CH$$s0   B) A#C) )
C&3.C!!C&)D*=#D%%D*c                     [         R                  " 5       nUR                  UR                  5        UR	                  5       nUR                  [        5        [        R                  " U SX2S9nUR                  U5        U$ )z7Returns an SMB connection to the sysvol share on the DCsysvol)lpcreds)	s3paramget_contextload
configfileget_smb_signingset_smb_signingr)   libsmbConn)serverrM   rN   s3_lpsaved_signing_stateconns         rI   smb_sysvol_connr[   q   sh     !E	JJr}}  //1	./;;vxE?D	-.K    c                  z    [         R                   R                  5       R                  5       R                  SS5      $ )N:r,   )datetimenow	isoformatreplace r\   rI   get_timestamprd      s-      ",,.66sC@@r\   c                 V    SU< SU< S3n[         R                  R                  X5      $ )Nzsamba-backup-r,   z.tar.bz2)ospathjoin)	targetdirnametime_strfilenames       rI   backup_filepathrm      s    /3X>H77<<	,,r\   c                 
  ^ [         R                  " S5      n[        U S5       m[        U4S jS5       H  nUR	                  U5        M     S S S 5        UR                  5       $ ! , (       d  f       UR                  5       $ = f)Nsha256rbc                  &   > T R                  S5      $ )Ni   )read)fs   rI   <lambda>"create_sha256sum.<locals>.<lambda>   s    !&&-r\   r\   )hashlibnewopeniterupdate	hexdigest)rl   hashchunkrs   s      @rI   create_sha256sumr~      sg    ;;x D	h	/5EKK 6 
 >> 
	 >>s   )A%%
Bc                     U R                  SU-  5        [        R                  " US5      nUR                  USS9  UR	                  5         g )NzCreating backup file %s...w:bz2z./arcname)r5   tarfilerx   addclose)r@   tmpdirrm   tfs       rI   create_backup_tarr      s=    
KK,>?	ow	/BFF64F HHJr\   c                    [        [        R                  R                  U S5      S5      n [        R                  R                  5       R                  S5      nUR                  SU-  5        UR                  SUR                  S5      -  5        UR                  SU< SU< S	35        UR                  S
UR                  S5      < SUR                  S5      R                  5       < S35        UR                  S[        U5      -  5        U(       a  UR                  SU-  5        UR                  5         g ! UR                  5         f = f)N
backup.txtwz%Y-%b-%d %H:%M:%SzBackup created %s
zUsing samba-tool version: %s
zserver stringzDomain z backup, using DC 'z'
zBackup for domain 	workgroup (NetBIOS), realmz (DNS realm)
z#Backup contains domain secrets: %s
z%s
)rx   rf   rg   rh   r_   r`   strftimewritegetlowerr7   r   )ri   rM   backup_typerW   include_secrets
extra_infors   rk   s           rI   create_log_filer      s    
 	RWW\\)\2C8A$$((*334GH	%01	0266/3JJK	{FKL	$bffWo&;&;&=? 	@	6_9MMNGGFZ'(			s   C<D9 9Ec                     [         R                  " 5       n[         R                  " U S5      Ul        [         R                  " U[         R
                  U5      X1'   U R                  U5        g )N@SAMBA_DSDB)r9   MessageDnr<   MessageElementFLAG_MOD_ADDmodify)r?   markervaluems       rI   add_backup_markerr      sF    A66%'AD""5#*:*:FCAI	LLOr\   c                 "   Uc  [        S5      e[        R                  R                  U5      (       d+  U R	                  SU-  5        [        R
                  " U5        g [        R                  R                  U5      (       d  [        SU-  5      eg )NzTarget directory requiredzCreating targetdir %s...z%s is not a directory)r   rf   rg   existsr5   makedirsisdir)r@   ri   s     rI   check_targetdirr      sn    67777>>)$$.:;
IWW]]9%%2Y>?? &r\   c                    UR                  5       nSU< S[        R                  < S3nSU< S3nUR                  UR	                  5       [
        R                  US9n[        US   S   5      n[        R                  " SS	5      nU R                  S
U< SU< 35        U R                  SU-  5        UR                  XGSUS9  g)zASets a randomly generated password for the backup DB's admin userz(objectsid=r,   )z(&(objectClass=user))r0   r/   
expressionr   samaccountname       zSetting z password in backup to: z7Run 'samba-tool user setpassword %s' after restoring DBF)force_change_at_next_loginusernameN)r6   r   DOMAIN_RID_ADMINISTRATORr8   	domain_dnr9   SCOPE_SUBTREEr7   sambagenerate_random_passwordr5   setpassword)r@   r?   	domainsidmatch_adminsearch_exprrE   r   	adminpasss           rI   set_admin_passwordr      s     $$&I)2)1)J)JLK/:<K ,,EOO-S5F5F"-  /C3q6*+,H..r26I
KK(INO
KKI 	k'  )r\   c                       \ rS rSrSrSr\R                  \R                  S.r	\
" SS\S9\
" S\S	S
9\
" SSSSS9\
" SSSSS/S\" 5       -  S9/r  SS jrSrg)cmd_domain_backup_online   a  Copy a running DC's current DB into a backup tar file.

Takes a backup copy of the current domain from a running DC. If the domain
were to undergo a catastrophic failure, then the backup file can be used to
recover the domain. The backup created is similar to the DB that a new DC
would receive when it joins the domain.

Note that:
- it's recommended to run 'samba-tool dbcheck' before taking a backup-file
  and fix any errors it reports.
- all the domain's secrets are included in the backup file.
- although the DB contents can be untarred and examined manually, you need
  to run 'samba-tool domain backup restore' before you can start a Samba DC
  from the backup file.z6%prog --server=<DC-to-backup> --targetdir=<output-dir>	sambaoptscredopts--serverThe DC to backuphelptype--targetdirz%Directory to write the backup file to)r   r   --no-secrets
store_trueF-Exclude secret values from the backup createdactiondefaultr   --backend-storechoiceBACKENDSTOREtdbmdb7Specify the database backend to be used (default is %s)r   metavarchoicesr   Nc                 &   U R                  5       nUR                  [        R                  5        UR	                  5       nUR                  U5      n	Uc  [        S5      e[        Xt5        [        R                  " US9n
U(       + n [        XyUXSU
US9nUR                  nA[        SU-   U	[        5       US9n[        X5      nUR                  5       nUR!                  S5        ["        R$                  R'                  U
S5      n[)        X8U	5      n[+        UUUR-                  5       5        [.        R0                  " UR2                  5        [        UR4                  [        5       U[6        R8                  S	9n[;        5       n[=        US
U5        [=        USU5        [=        USS5        U(       a  [?        UU5        [A        UUU5      n[C        XSX;5        [E        XzU5        [.        R0                  " U
5        g ! [.        R0                  " U
5        f = f)NServer requireddirSAMBA_INTERNAL)r@   rN   rM   r   rW   dns_backendri   backend_storeldap://urlcredentialssession_inforM   z$Backing up sysvol files (via SMB)...sysvol.tar.gzr   r   rM   flags
backupDatesidForRestore
backupTypeonline)#
get_loggersetLevelloggingDEBUGget_loadparmget_credentialsr   r   tempfilemkdtempr   pathsr   r   rJ   domain_dns_namer5   rf   rg   rh   r[   r   r6   shutilrmtreerL   r?   r9   FLG_DONT_CREATE_DBrd   r   r   rm   r   r   )selfr   r   rW   ri   
no_secretsr   r@   rM   rN   r   r   ctxr   
remote_samnew_sidr   
sysvol_tarsmb_connr?   rk   backup_files                         rI   runcmd_domain_backup_online.run   s   "&##%((, >011*!!i0 ).+	"FB-<)9V+8:C IIE 9v#55,:,<EJ)*=G..0E KK>?fo>J&v59H(J
0I0I0KL MM%,,' ekk8HR # 6 68E$He\8<e_g>e\8< "651 *)UHEKF&Jfk:MM&!FMM&!s   EG8 8Hrc   )NNNNFN)__name__
__module____qualname____firstlineno____doc__synopsisoptionsSambaOptionsCredentialsOptionstakes_optiongroupsr   r7   r   takes_optionsr   __static_attributes__rc   r\   rI   r   r      s     HH)).. 	z 2=}3;	=~lEC	E xu~!#<#>?	@
M IM,0="r\   r   c                       \ rS rSrSrSr\" SS\S9\" SS\S9\" S	S
\S9\" SSSSS9\" SSSSS9\" SS\S9/r\	R                  \	R                  S.rS rS rS rS rS rS r   SS jrSrg) cmd_domain_backup_restorei;  ah  Restore the domain's DB from a backup-file.

This restores a previously backed up copy of the domain's DB on a new DC.

Note that the restored DB will not contain the original DC that the backup
was taken from (or any other DCs in the original domain). Only the new DC
(specified by --newservername) will be present in the restored DB.

Samba can then be started against the restored DB. Any existing DCs for the
domain should be shutdown before the new DC is started. Other DCs can then
be joined to the new DC to recover the network.

Note that this command should be run as the root user - it will fail
otherwise.zQ%prog --backup-file=<tar-file> --targetdir=<output-dir> --newservername=<DC-name>z--backup-filezPath to backup filer   r   zPath to write toz--newservernamezName for new serverz	--host-ipstring	IPADDRESSzset IPv4 ipaddress)r   r   r   z
--host-ip6
IP6ADDRESSzset IPv6 ipaddressz--sitezSite to add the new server inr   c                    [        U5      nUR                  n	UR                  5       R                  5       n
UR                  R                  5       nUnUR                  R                  5       n[        UR                  5       5      n[        X)5      n[        X)5      n[        XU5      n[        XU5      nUc  Uc  [        S5      eUR                  SU-  5        UR                  S5        [        X.XyXXXVUUUSS9  g)zQ
Registers the new realm's DNS objects when a renamed domain backup
is restored.
Nz+Please specify a host-ip for the new serverzDNS realm was renamed to %sz*Populating DNS partitions for new realm...F)add_root)r   domaindnget_root_basednget_linearized	dnsdomainr   netbiosnamer   r6   r!   r"   r   r   r   r5   r    )r   r@   r?   rM   ntdsguidhost_iphost_ip6sitenamesr  forestdnr  	dnsforesthostnamer   dnsadmins_sid
domainguids                    rI   register_dns_zone+cmd_domain_backup_restore.register_dns_zone]  s     B>>((*99;OO))+		$$**,E0023	)%:#E4
 $F8%f(;?x/LMM1I=>@A 	!4!)i!(J!.	@r\   c                     UR                  5         [        USSSSS9n[        USS5        SS/n[        USS5        US	/-  nS
nSU/nUR                  XSS9  UR	                  5         g)z3Fixes attributes that reference the old/removed DCsTFquietfixyesin_transaction(fix_all_old_dn_string_component_mismatchALLlastKnownParentinterSiteTopologyGenerator!remove_plausible_deleted_DN_linkszmsDS-NC-Replica-Locationssearch_options:1:2r.   )r2   r1   Ntransaction_startr   setattrcheck_databasetransaction_commit)r   r?   chkr1   cross_ncs_ctrlr2   s         rI   fix_old_dc_references/cmd_domain_backup_restore.fix_old_dc_references~  s     	!e4Tu%)+ 	?G"$@A 	8%@-..-$n5H:  "r\   c                 6   [         nSR                  U5      nUR                  UR                  5       [        R
                  US9n[        U5      S:X  aE  UR                  SR                  U5      5        [        R                  " XR                  5       U5        U$ )z5Creates the default site, if it doesn't already existz(&(cn={0})(objectclass=site))r/   r   r   zCreating default site '{0}')
r   formatr8   get_config_basednr9   r   r;   r5   r&   create_site)r   r?   r@   sitenamer   rE   s         rI   create_default_site-cmd_domain_backup_restore.create_default_site  s     5<<XFll5224C<M<M&1  3 s8q=KK5<<XFGe%<%<%>Ir\   c                 n   / SQnUR                  [        R                  " US5      [        R                  US9n[        R                  " 5       n[        R                  " US5      Ul        U H5  nXSS   ;   d  M  [        R                  " / [        R                  U5      XE'   M7     UR                  U5        g)z-Remove DB markers added by the backup process)r   backupRenamer   r   r   r0   r/   r1   r   N)	r8   r9   r   r:   r   r<   r   FLAG_MOD_DELETEr   )r   r?   markersrE   r   attrs         rI   remove_backup_markers/cmd_domain_backup_restore.remove_backup_markers  s     Pllum <!$!(  *
 KKMvve]+D1v~,,R1D1DdK  	Qr\   c                     UR                  [        R                  " US5      [        R                  SS/S9nSUS   ;   a  [	        US   S   5      nU$ SUS   ;   a  SnU$ SnU$ )Nr   rA  r   rB  r   renamer   )r8   r9   r   r:   r7   )r   r?   rE   r   s       rI   get_backup_type)cmd_domain_backup_restore.get_backup_type  s    llum <!$"0,!?  A 3q6!c!f\23K  s1v%"K  #Kr\   c                    U H  n[        X5      n[        R                  " 5       nSUl        XER                  l        [        U5      UR                  l        [        U5      n[        R                  " 5       n[        R                  " X5      Ul        [        R                  " U[        R                  S5      US'   UR                  U5        M     g)z?Ensures the UTDV used by DRS is correct after an offline backup   replUpToDateVectorN)r'   r   replUpToDateVectorBlobversionctrcursorsr;   countr(   r9   r   r   r<   r   FLAG_MOD_REPLACEr   )r   r?   
partitionsncutdv	utdv_blob	new_valuer   s           rI   save_uptodate_vectors/cmd_domain_backup_restore.save_uptodate_vectors  s    B$U/D !779I !I$(MM!"%d)IMM +IA66%$AD&)&8&89<9M9M9M'OA"# LLO! r\   Nc	                 j   U(       a$  [         R                  R                  U5      (       d  [        S5      eUc  [        S5      e[         R                  R                  U5      (       aI  [         R                  " U5      (       a.  [         R
                  R                  S5      S:w  a  [        S5      eU(       d  [        S5      e[        R                  " 5       n	U	R                  [        R                  5        U	R                  [        R                  " [        R                  5      5        UR                  5       n[         R                  R!                  U5      n["        R$                  " U5      n
U
R'                  U5        U
R)                  5         [         R*                  " USS9  [         R                  R-                  US	S
5      n[.        R0                  " XS-   5        UR3                  5       nU(       a*  U	R5                  SU-  5        [.        R0                  " X5        [6        R8                  R;                  5       nUR=                  U5        [         R                  R-                  US5      n[         R                  R-                  US5      n[?        U[A        5       U[B        RD                  S9nU RG                  U5      nUc2  U RI                  UU	5      nU	R5                  SRK                  U5      5        URM                  S[B        RN                  S/S9nUS   R                  S5       Vs/ s H  n[Q        U5      PM     nnUS:X  a  U RS                  UU5        URU                  U5      n[W        U	UXUUS9nUUl,        UUl-        [6        R\                  R^                  [6        R\                  R`                  -  Ul1        U	R5                  S5        [e        XURf                  URh                  XMSS9  URM                  [B        Rj                  " US5      [B        RN                  S/S9nUS   R                  S5      S   nU	R5                  S[Q        U5      -   5         URm                  [o        [Q        U5      5      S9  [B        R                  " 5       n [B        Rj                  " US-5      U l@        [Q        UR                  5      n![B        R                  " S.U!-  [B        R                  S/5      U S/'   UR                  U 5        US0:X  a   U R                  U	UUUR                  XgU5        [         R                  R-                  US15      n"[        U"[A        5       U[B        RD                  S29n#[        U#URf                  URh                  UR                  UR                  UR                  UR                  UR                  [        R                  S39	  UR                  5       n$[6        R                  " UR                  5       5      n%S4U$4S5U%4/n&U& H"  u  n'n(U(U;   d  M  U R                  U'US S S S6S79  M$     S8 H  n'U R                  U'US6S79  M     S9n)URM                  UR                  5       [B        R                  U)S:9nU H5  n [Q        U R                  S;5      S   5      n*U*U:w  d  M(  [        UU	U*5        M7     U H  n+[B        R                  " 5       n,[B        Rj                  " UU+5      U,l@        [B        R                  " / [B        R                  S<5      U,S<'   [B        R                  " / [B        R                  S=5      U,S='   UR                  U,5        M     [        U5        [        U5        [         R                  R-                  US>5      n-UR                  S?S@5      n.[         R                  R                  U.5      (       d  [         R                  " U.5        [        U-U.UU5        [         R                  " U-5        U	R5                  SA5        U R                  U5        U R                  U5        U	R5                  SBU-  5        U	R5                  SC5        g s  snf ! [p         GaN  nURr                  u  nnU[B        Rt                  :w  a  e / n URM                  [B        Rj                  " USU-  5      [B        RN                  S/S S!/S"9nO;! [p         a.  nURr                  u  nnU[B        Rv                  :w  a  e  S nAOS nAff = f[y        U5      S#:w  a  e UR{                  SUS   S   S   5      nUR}                  S$5      nU	R                  S%U-  5        U	R                  S&5        U	R                  S'5        U	R                  S(U-  5        [        S)US   R                  < S*U< S+U< S,35      eS nAff = f)DNzBackup file not found.z!Please specify a target directorySAMBA_SELFTEST1zTarget directory is not emptyzServer name requiredi  )modeetczsmb.confz.origz&Using %s as restored domain's smb.confprivatesam.ldbr   zAdding new DC to site '{0}' namingContextsrB  r   offline)rN   rM   r  forced_local_samdbnetbios_namez#Updating basic smb.conf settings...z"active directory domain controller)rM   
serverroler   r   zCreating account with SID: )specified_sidr-   
objectGUIDzshow_deleted:0zshow_recycled:0)r0   r/   r1   r2   r3   zutf-8z|The RID Pool on the source DC for the backup in %s may be corrupt or in conflict with SIDs already allocated in the domain. zaRunning 'samba-tool dbcheck' on the source DC (and obtaining a new backup) may correct the issue.z@Alternatively please obtain a new backup against a different DC.zVThe SID we wish to use (%s) is recorded in @SAMBA_DSDB as the sidForRestore attribute.zCDomain restore failed because there is already an existing object (z) with SID z and objectGUID zT.  This conflicts with the new DC account we want to add for the restored domain.   z@ROOTDSEz	<GUID=%s>dsServiceNamerI  zsecrets.ldb)r   rM   r   )domainr   r  r  r   machinepasskey_version_numbersecure_channel_type	domaindns	forestdnsT)force)rA   pdcnaminginfrastructureschemaz*(&(objectClass=Server)(serverReference=*))r9  cnrepsFromrepsTor   rg   rL   z4Fixing up any remaining references to the old DCs...z'Backup file successfully restored to %szEPlease check the smb.conf settings are correct before starting samba.)^rf   rg   r   r   listdirenvironr   r   	getLoggerr   r   
addHandlerStreamHandlersysstdoutupperabspathr   rx   
extractallr   chmodrh   r   copyfileget_loadparm_pathr5   r   r   LoadParmrQ   r   r   r9   r   rJ  r>  r:  r8   r:   r7   rZ  r   r   nc_listfull_nc_listdsdbUF_SERVER_TRUST_ACCOUNTUF_TRUSTED_FOR_DELEGATIONuserAccountControlr   domain_namer   r   join_add_objectsr   r   r=   ERR_CONSTRAINT_VIOLATIONr>   r;   schema_format_valuedecodeerrorr<   r   	ntds_guidr   rT  r   r!  r   r   r  mynamedomsid	acct_passrn  r   SEC_CHAN_BDCr   dn_from_dns_nameforest_dns_nameseize_dns_role
seize_roler;  r   r   r   r   r	   remover6  rF  )/r   r   r   r   ri   newservernamer  r  r  r@   r   smbconfcli_smbconfrM   private_dir
samdb_pathr?   r   rE   rncsrN   r   rC   rF   rG   rH   dup_resdup_edup_enum_
objectguidr   r  secrets_pathsecrets_ldbr   	forest_dn	dns_rolesroler<   r   rw  rV  msgr   dest_sysvol_dirs/                                                  rI   r   cmd_domain_backup_restore.run  s9    { ; ;788BCCGGNN9%%"**Y*?*?JJNN+,3>??566""$&'//

;< &++- GGOOI.	\\+&
i 


' '',,y%<7!23  113KK@;NOOOK1[[!!#
 ggll9i8WW\\+y9
*>3C224**51< ++E6:DKK5<<TBC ll#.."2!3  5"1vzz*:;<;!s1v;< )#&&uc2
 ((,F%B/4)68 "'**"D"D"'**"F"F#G 	9:WS__YY	 D	F
 llum <!$"1!2  4 !fjj)!,1CH<=+	A  ws3x/@ AX KKMvveZ(&	 //i0G030D0D0?A/ 	Q
 ("""65"cmm#*d< ww||K?,^5E" # 6 68K"%))s}}(+

cjj(+/2/E/E040A0A	C OO%	**5+@+@+BC	!9-!9-/	!HD"Sy##D%tT#N "
 IDOOD%tO4 I
 Cll5224C<M<M&1  3AQUU4[^$B]"%,  B++-CVVE2&CF!00141E1E1;=C
O  ..r/2/C/C/79CM LL  	'u-&u- WW\\)_=
&&2ww~~o..KK(z?E7C
		* 	JK""5) 	""5)=	IJ & 	'I =J  )	A66LT4s333G	,,CFF5*s:J,K-0^^.:^1A1B1D ' E
   %

1s555 6
 G!22<7>qz,7OPQ7RTJ#**73JLL + .99 : LL R SLL 3 4LL G    !(
sJ @ A AG)	AsI   .a!a f2$&f-;cf-
c?$c:5f-:c??B.f--f2rc   )NNNNNNNN)r   r   r  r  r  r  r   r7   r	  r  r  r  r  r!  r6  r>  rF  rJ  rZ  r   r
  rc   r\   rI   r  r  ;  s    ,H 	%:E}#5C@ '<3G{;(	*|(L(	*x=CH	M ))..
@B#2&"( >BGKa'r\   r  c                       \ rS rSrSrSr\R                  \R                  S.r	\
" SS\S9\
" SS	\S9\
" S
SSSS9\
" SSSSS9\
" SSSSS/S\" 5       -  S9/rSS/rS rS rS rS r   S!S jrS rg)"cmd_domain_backup_renamei  an  Copy a running DC's DB to backup file, renaming the domain in the process.

Where <new-domain> is the new domain's NetBIOS name, and <new-dnsrealm> is
the new domain's realm in DNS form.

This is similar to 'samba-tool backup online' in that it clones the DB of a
running DC. However, this option also renames all the domain entries in the
DB. Renaming the domain makes it possible to restore and start a new Samba
DC without it interfering with the existing Samba domain. In other words,
you could use this option to clone your production samba domain and restore
it to a separate pre-production environment that won't overlap or interfere
with the existing production Samba domain.

Note that:
- it's recommended to run 'samba-tool dbcheck' before taking a backup-file
  and fix any errors it reports.
- all the domain's secrets are included in the backup file.
- although the DB contents can be untarred and examined manually, you need
  to run 'samba-tool domain backup restore' before you can start a Samba DC
  from the backup file.
- GPO and sysvol information will still refer to the old realm and will
  need to be updated manually.
- if you specify 'keep-dns-realm', then the DNS records will need updating
  in order to work (they will still refer to the old DC's IP instead of the
  new DC's address).
- we recommend that you only use this option if you know what you're doing.
zR%prog <new-domain> <new-dnsrealm> --server=<DC-to-backup> --targetdir=<output-dir>r   r   r   r   r   z"Directory to write the backup filez--keep-dns-realmr   Fz6Retain the DNS entries for the old realm in the backupr   r   r   r   r   r   r   r   r   r   new_domain_namenew_dns_realmc                    UR                  5       nUR                  U[        R                  S/SS9nUR	                  5       nU GH  nUS    GH  n	[        U	5      n	UR                  n
X9;   d  M"  [        R                  " SU-  UU	5      nUR                  SU< SU
< 35        [        R                  " 5       nXl        [        R                  " U[        R                  S5      US'   UR                  U5        U(       d  M  UR                  SU	< SU
< 35        [        R                  " U	[        R                  S5      US'   UR                  U5        GM
     GM     g	)
z?Updates dnsRoot for the partition objects to reflect the renamednsRootz$(&(objectClass=crossRef)(dnsRoot=*))r0   r/   r1   r   z%s$zAdding z dnsRoot to z	Removing z dnsRoot from N)get_partitions_dnr8   r9   SCOPE_ONELEVELr   r7   r<   resubr5   r   r   r   r   rC  )r   r@   r?   	old_realmdelete_old_dnspartitions_dnrE   	new_realmres_msgdns_rootr<   new_dns_rootr   s                rI   update_dns_root(cmd_domain_backup_rename.update_dns_root  s5    //1llS5G5G"+&L  N ))+	 G#I.x=ZZ(#%66%)*;Y*2$4LKK\2 NOAD#&#5#5l696F6F6?$AAiL LLO &~XEG%I J'*'9'9(:=:M:M:C(E) Q- / r\   c                 V   UR                  5       n[        R                  " [        U5      5      nUR	                  5       nUR                  U[        R                  S/SU-  S9nUR                  SU-  5        [        R                  " 5       nUS   R                  Ul	        [        R                  " U[        R                  S5      US'   UR                  U5        SU< SU< 3n	UR                  SUS   R                  < S	U	< 35        UR                  US   R                  U	S
/S9  g)z?Renames the domain partition object and updates its nETBIOSNamenETBIOSNamez	ncName=%sr  z+Changing backup domain's NetBIOS name to %sr   zCN=,z	Renaming z --> zrelax:0r2   N)get_default_basednr9   binary_encoder7   r  r8   r  r5   r   r<   r   rT  r   rI  )
r   r@   r?   new_netbios_namebase_dnnc_namer  rE   r   new_dns
             rI   rename_domain_partition0cmd_domain_backup_rename.rename_domain_partition  s   
 **,##CL1//1llS5G5G"/&1G&;  = 	A$% 	&KKM1vyy--.>.1.B.B.;=- 	Q  0?CFIIv>?SVYY)=r\   c                 $   UR                  5       nSU< SU< 3nUR                  SU-  5        UR                  US/5        UR                  5       R	                  5       nSU< SU< 3nUR                  SU-  5        UR                  US/5        g )NzDC=z#,CN=MicrosoftDNS,DC=DomainDnsZones,zDeleting old DNS zone %sztree_delete:1z
DC=_msdcs.z#,CN=MicrosoftDNS,DC=ForestDnsZones,)r  r5   deleter  r  )r   r@   r?   r  basednr<   r  s          rI   delete_old_dns_zones-cmd_domain_backup_rename.delete_old_dns_zones6  s    ))+=FO.34R/*+((*99;DMDLN.34R/*+r\   c                     UR                  5         [        USSSSS9n[        USS5        SnSU/nUR                  US9  UR	                  5         g	)
z@Fixes attributes (i.e. objectCategory) that still use the old DNTFr$  r)  r*  r.  r.   r  Nr/  )r   r?   r4  r5  r2   s        rI   fix_old_dn_attributes.cmd_domain_backup_rename.fix_old_dn_attributesC  s`     	!e4Tu%)+ 	?G-$n5H-  "r\   Nc
                 z   U R                  5       n
U
R                  [        R                  5        UR	                  5       nUR                  U5      nUc  [        S5      e[        X5        U(       + nUR                  5       nUR                  5       n[        R                  " U5      nU
R                  SU-  5        U
R                  SU-  5        U
R                  SU-  5        [        R                  " US9nU(       + n[        XX*XUSX_U	S9nUR                   nUU:X  a!  ["        R$                  " U5        [        S5      eUR&                  nUU:X  a!  ["        R$                  " U5        [        S	5      eUR)                  5         U?UR,                  n[/        S
U-   U[1        5       US9n[3        UU
5      n[4        R6                  R9                  US5      n[;        X[U5      n[=        UUUR?                  5       5        URA                  URB                  5        [/        URD                  [1        5       U[F        RH                  S9n[K        5       n[M        USU5        [M        USU5        [M        USU5        [M        USS5        U RO                  U
UUU5        U RQ                  U
UU5        U(       a  U RS                  U
UU5        U
R                  S5        U RU                  U5        U(       a  [W        U
U5        [Y        XbU5      n[[        XSUUSU< SU< S35        []        XU5        ["        R$                  " U5        g )Nr   z"New realm for backed up domain: %sz$New base DN for backed up domain: %szNew domain NetBIOS name: %sr   r   )r@   rN   rM   r   r   rW   ri   r   z+Cannot use the current domain NetBIOS name.z(Cannot use the current domain DNS realm.r   r   r   r   r   r   rA  r   rI  z$Fixing DN attributes after rename...zOriginal domain r   z (DNS realm))/r   r   r   INFOr   r   r   r   r   r  r   r  r5   r   r   r   r  r   r   r   do_joinlocal_samdbr   r   r   rJ   rf   rg   rh   r[   r   r6   rQ   r  r?   r9   r   rd   r   r  r  r  r  r   rm   r   r   )r   r  r  r   r   rW   ri   keep_dns_realmr   r   r@   rM   rN   r  new_base_dnr   r   r   
old_domainr  r   r   r   r   r   r?   rk   r   s                               rI   r   cmd_domain_backup_rename.runQ  s    "%##%((, >011*++%++-)//1,,];8=HI:[HI1OCD!!i0 ).%k&3,16E2B-34AC __
(MM&!LMMII	%MM&!IJJ 	 O		 y61u(6(8RA
%j&9 WW\\&/:
"6u5h
J,E,E,GH 	%++N4D224 !?%x8%':%;%x8 	VUI~F 	$$VUOD%%feY?:;""5) vu- &iIHfo#Y0	1 	&+6fr\   rc   )NNNNFFN)r   r   r  r  r  r  r  r  r  r  r   r7   r   r	  
takes_argsr  r  r  r  r   r
  rc   r\   rI   r  r    s    8+H )).. 	z 2=}#G	!,L	N~lEC	E xu~!#<#>?	@M $_5J#(N>4,# =AGL,0gr\   r  c                   v    \ rS rSrSrSrS\R                  0r\	" SS\
S9/rSrS	 rS
 rS rS rS rSS jrSrg)cmd_domain_backup_offlinei  ay  Backup the local domain directories safely into a tar file.

Takes a backup copy of the current domain from the local files on disk,
with proper locking of the DB to ensure consistency. If the domain were to
undergo a catastrophic failure, then the backup file can be used to recover
the domain.

An offline backup differs to an online backup in the following ways:
- a backup can be created even if the DC isn't currently running.
- includes non-replicated attributes that an online backup wouldn't store.
- takes a copy of the raw database files, which has the risk that any
  hidden problems in the DB are preserved in the backup.z%prog [options]r   r   zOutput directory (required)r   z.bak-offlinec                    XR                   -   n [        XSS9  [        R                  R                  U5      (       d  Sn[        UR                  U5      5      eg ! [         aj  n [        R                  " U5        Ue! [
         a?  n[        US5      (       a'  UR                  [        R                  :X  a	   S nA S nAg UeS nAff = fS nAf[         a  n[        UR                  U5      eS nAff = f)NT)readonlyerrnoz1tdbbackup said backup succeeded but {0} not found)
backup_extr#   r%   r   rx   	Exceptionhasattrr  EINVALFileNotFoundErrorr   strerrorrf   rg   r   r:  )r   rg   backup_pathcopy_errrF   ss         rI   offline_tdb_copy*cmd_domain_backup_offline.offline_tdb_copy  s    __,	.T6" ww~~k**CAqxx455 +! " 
	
 N	  1g&&177ell+BF ! 	.qzz1--	.sM   
A 
C2&A><C
>
C/C7C
 CCC

C2C--C2c                 4    [        XU R                  -   5        g N)r$   r  )r   rg   s     rI   offline_mdb_copy*cmd_domain_backup_offline.offline_mdb_copy  s    doo-.r\   c                 4   [         R                  R                  US5      n[        US-   U[        R
                  S9nUR                  SU-   5        UR                  5         U R                  US-   5        U R                  US-   5        UR                  5         g )Nsecrets.ldbrM   r   Starting transaction on .tdb)
rf   rg   rh   r   r9   r   r5   r0  r  transaction_cancel)r   r  rM   r@   r  secrets_objs         rI   backup_secrets(cmd_domain_backup_offline.backup_secrets  s    ww||K;,/B # 6 68.=>%%'lV34lV34&&(r\   c                    [         R                  R                  US5      nSnUR                  S[        R
                  U/S9nXgS   ;   =(       a    [        US   U   S   5      S:H  nS n	S n
U(       a.  UR                  S5        U R                  n
UR                  5       n	O0UR                  SU-   5        U R                  n
UR                  5         UR                  S	U-   5        U R                  U5        US
-   n[         R                  " U5       H  n[         R                  R                  X5      nUR                  S5      (       a  UR                  SU-   5        U
" U5        MV  UR                  S5      (       a'  UR                  SU-   5        U R                  U5        M  UR                  SU-   5        [        R                  " XU R                   -   5        M     [#        X$5      nU(       a  A	U$ UR%                  5         U$ )Nrb  backendStorez
@PARTITIONrB  r   r   z1MDB backend detected.  Using mdb backup function.r  z   backing up z.dr  z"   backing up locked/related file r  z$   tdbbackup of locked/related file z   copying locked/related file )rf   rg   rh   r8   r9   r:   r7   r5   r  search_iteratorr  r0  rz  endswithr   r  r  rJ   r  )r   r  r?   rM   r@   sam_ldb_pathstore_labelrE   mdb_backendres_iteratorcopy_function	sam_ldb_dsam_filerC   s                 rI   backup_smb_dbs(cmd_domain_backup_offline.backup_smb_dbs  s   ww||K; %llCNN"-  0!V+TCF;4G4J0Ku0T KKKL 11M !002LKK2\AB 11M##%$|34l+ 4'	

9-Hww||I8H  ((@8KLh'""6**BXMN%%h/=HIT__*DE . "%0 
 $$&
r\   c                 t   UR                   UR                  [        R                  R	                  UR
                  5      S.nUR                  5        VVs/ s H   u  pEUR                  U5      (       d  M  XE4PM"     nnnUS   u  px[        U5      S:  a  [        US S9u  pxXq[        U5      S  -  nU$ s  snnf )N)ra  stater`  r   r3   c                     [        U S   5      $ )Nr3   )r;   )ps    rI   rt   8cmd_domain_backup_offline.get_arc_path.<locals>.<lambda>I  s    QqTr\   )key)
r  	state_dirrf   rg   dirnamer  items
startswithr;   max)	r   rg   
conf_pathsbackup_dirsr  r  matching_dirsarc_pathfs_paths	            rI   get_arc_path&cmd_domain_backup_offline.get_arc_path>  s    ","8"8 * 4 4 ggooj.@.@AC /:.?.?.A -.AFQ+  !.A -)!, }! #M7J KHW''-s   B45B4Nc           	         [         R                  " 5       nUR                  [         R                  5        UR	                  [         R
                  " [        R                  5      5        UR                  5       n[        R                  R                  XDR                  S5      5      nUR                  (       a.  [        R                  R!                  UR                  5      (       d5  UR#                  SR%                  UR                  5      5        ['        S5      e[)        X25        UR*                  UR,                  [        R                  R/                  UR0                  5      /nUR3                  SR%                  SR5                  U5      5      5        / n[7        5       nU GH  n	[        R8                  " U	5       GHk  u  pnU
R;                  UR<                  5      (       a  M)  U
R?                  S5      (       d  SU
;   a  MG  U
R;                  [        R                  R5                  UR@                  S5      5      (       a  M  U H  n[        R                  R5                  X5      n [        RB                  " US	S
9nURH                  URJ                  4U;   a  MV  UR?                  U RL                  5      (       a  [        RN                  " U5        M  UR?                  S5      (       a  M  URQ                  U5        URS                  URH                  URJ                  45        M     GMn     GM     [U        UR                  [W        5       U[X        RZ                  S9nU R]                  UR*                  XC5        U R_                  UR*                  UXC5      nURa                  5       n[b        Rd                  " U5      nURg                  5         A[i        UR                  U RL                  -   [W        5       US/[X        RZ                  S9n[k        5       n[m        USU5        [m        USU5        [m        USS5        URg                  5         AU H  n[        R                  R!                  UU RL                  -   5      (       a  M6  UR?                  S5      (       aq  UR3                  SU-   5        [i        UU[X        RZ                  S9nURo                  5         UR3                  S5        U Rq                  U5        URs                  5         M  UR?                  S5      (       d  M  UR3                  SU-   5        U Rq                  U5        M     [t        Rv                  " USS9n[        R                  R5                  US5      n[x        Rz                  " US5      nUR3                  S5        Sn[        R                  R5                  UU5      n[}        UR<                  UUR0                  U5        URS                  UU5        [        RN                  " U5        [        UUSSS 5        [        R                  R5                  US!5      nURS                  U[        R                  R                  U5      5        [        RN                  " U5        UR3                  S"5        / nU GH  nU R                  UU5      n[        R                  R!                  UU RL                  -   5      (       a  UR3                  S#U-   U RL                  -   S$-   5        URQ                  [        UU RL                  -   5      < S%U< 35        URS                  UU RL                  -   US&9  [        RN                  " UU RL                  -   5        M  UR?                  S5      (       d  UR?                  S5      (       a  UR3                  S'U-   5        GM  [        R                  R                  U5      (       d  GME  UR3                  S(U-   5        URQ                  [        U5      < S%U< 35        URS                  UUS&9  GM     [        R                  R5                  US)5      n[{        US*5       n U H  n!U R                  U!S+-   5        M     S S S 5        URS                  U[        R                  R                  U5      5        [        RN                  " U5        UR                  5         [        R                  " U[        R                  R5                  US,R%                  U5      5      5        [        R                  " U5        UR3                  S-5        g ! [D         a    URG                  U S35         GM  f = f! , (       d  f       N= f).Nr   zNo database found at {0}zCPlease check you are root, and are running this command on an AD DCzrunning backup on dirs: {0} z.sockz.sock/dnsF)follow_symlinksz does not exist!r   zmodules:)r   r   rM   r  r   r   r   r   re  r  z!Starting transaction on solo db: r  z%   running tdbbackup on the same filer  z#running tdbbackup on lone tdb file INCOMPLETEsambabackupfile)r   prefixzsamba-backup.tar.bz2r   z&running offline ntacl backup of sysvolr   	localhostTr   zbuilding backup tarz   adding backup z to tar and deleting filez  r   z   skipping z   adding misc file 	SHA256SUMr   
zsamba-backup-{0}.tar.bz2zBackup succeeded.)Hr   r|  r   r   r}  r~  r  r  r   r   	provisionprovision_paths_from_lpr   r?   rf   rg   r   r  r:  r   r   r  r  r  r  r5   rh   setwalkr  rL   r  binddns_dirstatr  warningst_inost_devr  r  appendr   r   r   r9   r   r  r  r6   r   r   
disconnectr   rd   r   r0  r  r  r   r   r   rx   r
   r   basenamer  r~   isfiler   r   rI  rmdir)"r   r   ri   r@   rM   r   r  	all_files	all_stats
backup_dirworking_dirr  	filenamesrl   	full_pathr  r?   rC   dom_sid_strr   rk   rg   ldb_objtemp_tar_dirtemp_tar_nametarsysvol_tar_fnr   	backup_fnchksum_listr  chksum_filepathrs   cs"                                     rI   r   cmd_domain_backup_offline.runN  s   ""$&'//

;< ##%77FF7OLu{{ ; ;LL3::5;;GH  F G G 	* ((%//wwu}}57188+9NOP 	E	%J/1wwz/B+))%,,77''00H4K ))"'',,u7H7H%*PQQ )H "[ CI
!GGIuE
 !((+y8   ((99		),   ((11 $$Y/MM188QXX"675 !* 0C &T %++N4D224 	E--r:!!%"3"3UBG **,"";/
 	 doo5#1#3)l#2H2HJ !?%x8%#6%y9 	 D77>>$"899==((KK Cd JK!$2S5K5KLG--/KK GH))$/..0]]6**KK E LM))$/   ''I/JL\3IJll='2<='WW\\,>
u||ZH
M*
		*b)[$GGGLL|<		277++I67
		))*D((u5Hww~~dT__455/(:T__L78 9"" 01G H (*+ t.A		$01v&&$--*?*?NX56%%2X=>""$4T$:$,$. / h/% ( '',,|[A/3'1 D! ! ( 	!1!1/!BC
		/"		
		-'',,y9@@JL	M 	'(A - !)4D'EF !j ('s   (d>e$>e!	 e!	$
e2rc   )NN)r   r   r  r  r  r  r  r  r  r   r7   r	  r  r  r  r  r  r  r   r
  rc   r\   rI   r  r    sb    @ !HW))
 	}1	M  J62/
)8v o)r\   r  c                   N    \ rS rSrSr\" 5       \" 5       \" 5       \" 5       S.r	Sr
g)cmd_domain_backupi   z)Create or restore a backup of the domain.)re  r   rI  restorerc   N)r   r   r  r  r  r  r   r  r  subcommandsr
  rc   r\   rI   rI  rI     s$    379575779;Kr\   rI  r  )`r_   rf   r  r   r   r   r   r   samba.getoptgetoptr  samba.samdbr   r   r9   r   samba.samba3r   rU   r   rO   samba.ntaclsr   r	   r
   
samba.authr   
samba.joinr   r   r   samba.dcerpc.securityr   samba.netcmdr   r   samba.dcerpcr   r   r   r   samba.netcmd.fsmor   samba.provisionr   r   samba.upgradehelpersr   samba.remove_dcr   r   samba.dbcheckerr   r  r   r   r   samba.provision.sambadnsr    r!   r"   samba.tdb_utilr#   samba.mdb_utilr$   r  
subprocessr%   r&   
samba.dsdbr'   	samba.ndrr(   samba.credentialsr)   r*   r   rv   rJ   r[   rd   rm   r~   r   r   r   r   r   netcmdCommandr   r  r  r  SuperCommandrI  rc   r\   rI   <module>re     s>  $  	 
     
  8 
  8 ) F F % I I ) - 1 1  , 5 ? % / # 	 N N6 6 $ #  )  (  2 ) -%`A-
  $,@),_"u||33 _"DC' C'Lwu||33 wtB) 4 4 B)J
;11 ;r\   