
    b                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z d dlmZmZ d dlZd dlmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ d dlmZmZmZ d d	l m!Z! d d
l"m#Z#m$Z$ d dl%m&Z&m'Z'm(Z( d dlm)Z) ddl*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2 d dl,m3Z3 d dl4m5Z5 d dl6Z6d dl,m7Z7m8Z8m9Z9 d dl:m;Z;m<Z<m=Z= d dl>m?Z? d dl@mAZA d dlBZBd dlCmDZD d dlmEZE d dlFmGZG d dlHmIZI d dlJmKZK d ZLd ZMd ZNd  ZOd! ZP	 d0d"ZQd# ZRd$ ZSd% ZT G d& d'ejU        jV                  ZW G d( d)e+          ZX G d* d+ejU        jV                  ZY G d, d-ejU        jV                  ZZ G d. d/ejU        j[                  Z\dS )1    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_REQUIREDc                    	 |                                  }nL# t          $ r?}|                    d           |                    d           t          d|          d }~ww xY wt	          |                                           }t          |          dz   t          |          z   }	 |                     t          j	        d|z  g ddg          }t          |          d	k    rt          d
|z            t          d|d|d         j        d          # t          j        $ r%}|j        \  }}	|t          j        k    r Y d }~nd }~ww xY wt          |          dz   t          |          z   S )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controlsr   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_restorerI   @   s   	8!!## 8 8 8 5 	6 	6 	6 	 3 	4 	4 	4 137778 %&&((
)
)C#hhns3xx/Oll *_ <!#%5%6%8  9 9
 s88q==  I  / / 0 0 0 l ,OOSVYYY	8 9 9 	9
 <   vt3))) *)))) s88c>CHH$$s-    
A :AA 'A.D E	$EE	c                    t          j                    }|                    |j                   |                                }|                    t                     t          j        | d||          }|                    |           |S )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)serverrL   rM   s3_lpsaved_signing_stateconns         rH   smb_sysvol_connrZ   p   s     !!E	JJr}  //11	.///;vxE???D	-...K    c                      t           j                                                                                             dd          S )N:r,   )datetimenow	isoformatreplace r[   rH   get_timestamprc      s3      "",,..66sC@@@r[   c                 T    d|d|d}t           j                            | |          S )Nzsamba-backup-r,   z.tar.bz2)ospathjoin)	targetdirnametime_strfilenames       rH   backup_filepathrl      s,     /3ttXXX>H7<<	8,,,r[   c                     |                      d|z             t          j        |d          }|                    |d           |                                 d S )NzCreating backup file %s...w:bz2z./arcname)r4   tarfileopenaddclose)r?   tmpdirrl   tfs       rH   create_backup_tarrw      sR    
KK,>???	ow	/	/BFF64F   HHJJJJJr[   c                    t          t          j                            | d          d          }	 t          j                                                            d          }|                    d|z             |                    d|                    d          z             |                    d|d|d	           |                    d
|                    d          d|                    d          	                                d           |                    dt          |          z             |r|                    d|z             |                                 d S # |                                 w xY w)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
)rr   re   rf   rg   r^   r_   strftimewritegetlowerr6   rt   )rh   rL   backup_typerV   include_secrets
extra_infofrj   s           rH   create_log_filer      s]   
 	RW\\)\22C88A$((**334GHH	%0111	0266/3J3JJKKK	{{{FFFKLLL	$$$$bffWoo&;&;&=&=&=&=? 	@ 	@ 	@	6_9M9MMNNN 	)GGFZ'(((										s   D#E) )E?c                     t          j                    }t          j        | d          |_        t          j        |t           j        |          ||<   |                     |           d S )N@SAMBA_DSDB)r8   MessageDnr;   MessageElementFLAG_MOD_ADDmodify)r>   markervaluems       rH   add_backup_markerr      sN    A6%''AD"5#*:FCCAfI	LLOOOOOr[   c                 $   |t          d          t          j                            |          s.|                     d|z             t          j        |           d S t          j                            |          st          d|z            d S )NzTarget directory requiredzCreating targetdir %s...z%s is not a directory)r   re   rf   existsr4   makedirsisdir)r?   rh   s     rH   check_targetdirr      s    67777>>)$$ @.:;;;
IW]]9%% @2Y>???@ @r[   c                    |                                 }d|dt          j        d}d|d}|                    |                                t
          j        |          }t          |d         d                   }t          j	        dd	          }| 
                    d
|d|           | 
                    d|z             |                    ||d|           dS )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)r5   r   DOMAIN_RID_ADMINISTRATORr7   	domain_dnr8   SCOPE_SUBTREEr6   sambagenerate_random_passwordr4   setpassword)r?   r>   	domainsidmatch_adminsearch_exprrD   r   	adminpasss           rH   set_admin_passwordr      s    $$&&II)2)1)J)J)JLKK/:{{<K ,,EOO--S5F"-  / /C3q6*+,,H.r266I
KKK(((IINOOO
KKI   	k9'  ) ) ) ) )r[   c                       e Zd ZdZdZej        ej        dZ e	dde
           e	de
d	           e	d
ddd           e	dddddgd e            z            gZ	 	 ddZdS )cmd_domain_backup_onlinea  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           
         |                                  }|                    t          j                   |                                }|                    |          }	|t          d          t          ||           t          j	        |          }
| }	 t          ||	|||d|
|          }|j        }~t          d|z   |	t                      |          }t          ||          }|                                }|                    d           t"          j                            |
d          }t)          |||	          }t+          |||                                           t/          j        |j                   t          |j        t                      |t6          j        	          }t;                      }t=          |d
|           t=          |d|           t=          |dd           |rt?          ||           tA          |||          }tC          |
|d||           tE          ||
|           t/          j        |
           d S # t/          j        |
           w xY w)NServer requireddirSAMBA_INTERNAL)r?   rM   rL   r   rV   dns_backendrh   backend_storeldap://urlcredentialssession_inforL   z$Backing up sysvol files (via SMB)...sysvol.tar.gzr   r   rL   flags
backupDatesidForRestore
backupTypeonline)#
get_loggersetLevelloggingDEBUGget_loadparmget_credentialsr   r   tempfilemkdtempr   pathsr   r   rI   domain_dns_namer4   re   rf   rg   rZ   r   r5   shutilrmtreerK   r>   r8   FLG_DONT_CREATE_DBrc   r   r   rl   r   rw   )selfr   r   rV   rh   
no_secretsr   r?   rL   rM   ru   r   ctxr   
remote_samnew_sidr}   
sysvol_tarsmb_connr>   rj   backup_files                         rH   runzcmd_domain_backup_online.run   sg   ""&&&##%%((,, >0111	***!i000 ).+	"F%B-<V)9V+8: : :C IE 9v#55,:,<,<E E EJ)*f==G..00E KK>???fo>>J&vr599H(J
0I0I0K0KLLL M%,''' ek8H8HR # 68 8 8E$He\8<<<e_g>>>e\8<<<  2"65111 *)UHEEKFB&/JJJffk:::M&!!!!!FM&!!!!s   FI
 
I )NNNNFN)__name__
__module____qualname____doc__synopsisoptionsSambaOptionsCredentialsOptionstakes_optiongroupsr   r6   r   takes_optionsr   rb   r[   rH   r   r      s          HH).  	z 2===}3;	= 	= 	=~lEC	E 	E 	E xu~!#<#<#>#>?	@ 	@ 	@
M IM,0=" =" =" =" =" ="r[   r   c            
       
   e Zd ZdZdZ edde           edde           edd	e           ed
ddd           edddd           edde          gZej	        ej
        dZd Zd Zd Zd Zd Zd Z	 	 	 ddZdS )cmd_domain_backup_restorea  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                 f   t          |          }|j        }	|                                                                }
|j                                        }|}|j                                        }t          |                                          }t          ||	          }t          ||	          }t          |||          }t          |||          }||t          d          |                    d|z             |                    d           t          ||||	|
||||||||d           dS )zi
        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   r5   r"   r#   r   r    r   r4   r!   )r   r?   r>   rL   ntdsguidhost_iphost_ip6sitenamesr   forestdnr  	dnsforesthostnamer   dnsadmins_sid
domainguids                    rH   register_dns_zonez+cmd_domain_backup_restore.register_dns_zoneT  sF    B>((**99;;O))++		$**,,E002233	)%::#E844
 $FB88%fb(;;?x/LMMM1I=>>>@AAA 	!	4!)9i!((J!.	@ 	@ 	@ 	@ 	@ 	@r[   c                    |                                  t          |dddd          }t          |dd           ddg}t          |dd           |d	gz  }d
}d|g}|                    ||           |                                 dS )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         rH   fix_old_dc_referencesz/cmd_domain_backup_restore.fix_old_dc_referencesu  s     	!!!e4Tu%)+ + + 	?GGG"$@A 	8%@@@-..-$n5HE:::  """""r[   c                 l   t           }d                    |          }|                    |                                t          j        |          }t          |          dk    rP|                    d                    |                     t          j	        ||                                |           |S )z5Creates the default site, if it doesn't already existz(&(cn={0})(objectclass=site))r/   r   r   zCreating default site '{0}')
r   formatr7   get_config_basednr8   r   r:   r4   r'   create_site)r   r>   r?   sitenamer   rD   s         rH   create_default_sitez-cmd_domain_backup_restore.create_default_site  s     5<<XFFll52244C<M&1  3 3 s88q==KK5<<XFFGGGeU%<%<%>%>IIIr[   c                 `   g d}|                     t          j        |d          t          j        |          }t          j                    }t          j        |d          |_        |D ]/}||d         v r#t          j        g t          j        |          ||<   0|                    |           dS )z-Remove DB markers added by the backup process)r   backupRenamer   r   r   r0   r/   r1   r   N)	r7   r8   r   r9   r   r;   r   FLAG_MOD_DELETEr   )r   r>   markersrD   r   attrs         rH   remove_backup_markersz/cmd_domain_backup_restore.remove_backup_markers  s     POOllum < <!$!(  * *
 KMMve]++ 	L 	LDs1v~~,R1DdKK$Qr[   c                     |                     t          j        |d          t          j        ddg          }d|d         v rt	          |d         d                   }nd|d         v rd}nd}|S )Nr   r*  r   r+  r   renamer   )r7   r8   r   r9   r6   )r   r>   rD   r   s       rH   get_backup_typez)cmd_domain_backup_restore.get_backup_type  s    llum < <!$"0,!?  A A 3q6!!c!f\233KKs1v%%"KK"Kr[   c                    |D ]}t          ||          }t          j                    }d|_        ||j        _        t          |          |j        _        t          |          }t          j
                    }t          j        ||          |_        t          j        |t          j        d          |d<   |                    |           dS )z?Ensures the UTDV used by DRS is correct after an offline backup   replUpToDateVectorN)r(   r   replUpToDateVectorBlobversionctrcursorsr:   countr)   r8   r   r   r;   r   FLAG_MOD_REPLACEr   )r   r>   
partitionsncutdv	utdv_blob	new_valuer   s           rH   save_uptodate_vectorsz/cmd_domain_backup_restore.save_uptodate_vectors  s     	 	B$UB//D !799I !I$(IM!"%d))IM ++IA6%$$AD&)&89<9M9M'O 'OA"# LLOOOO!	 	r[   Nc	                    |rt           j                            |          st          d          |t          d          t           j                            |          rFt          j        |          r2t           j                            d          dk    rt          d          |st          d          t          j                    }	|		                    t          j
                   |	                    t          j        t          j                             |                                }t           j                            |          }t#          j        |          }
|
                    |           |
                                 t           j                            |dd          }t-          j        ||d	z              |                                }|r-|	                    d
|z             t-          j        ||           t4          j                                        }|                    |           t           j                            |d          }t           j                            |d          }t=          |t?                      |t@          j!                  }| "                    |          }|>| #                    ||	          }|	                    d$                    |                     |%                    dt@          j&        dg          }d |d                             d          D             }|dk    r| '                    ||           |(                    |          }tS          |	|||||          }||_*        ||_+        t4          j,        j-        t4          j,        j.        z  |_/        |	                    d           ta          |||j1        |j2        ||d           |%                    tA          j3        |d          t@          j&        dg          }|d                             d          d         }|	                    dti          |          z              	 |5                    tm          ti          |                               no# tn          $ ra}|j8        \  }}|t@          j9        k    r g }	 |%                    tA          j3        |d|z            t@          j&        dgdd g!          }n2# tn          $ r%}|j8        \  }}|t@          j:        k    r Y d }~nd }~ww xY wtw          |          d"k    r |<                    d|d         d         d                   }|=                    d#          }|	>                    d$|z             |	>                    d%           |	>                    d&           |	>                    d'|z             t          d(|d         j?        d)|d*|d+          d }~ww xY wtA          j@                    }tA          j3        |d,          |_?        ti          |jA                  } tA          jB        d-| z  t@          jC        d.          |d.<   |D                    |           |d/k    r | E                    |	|||jA        |||           t           j                            |d0          }!t          |!t?                      |t@          j!        1          }"t          |"|j1        |j2        |jH        |jI        |jJ        |jK        |jL        t          jN        2	  	         |O                                }#t5          jP        |Q                                          }$d3|#fd4|$fg}%|%D ]$\  }&}'|'|v r| R                    |&|d d d d56           %d7D ]}&| S                    |&|d56           d8}(|%                    |T                                t@          jU        |(9          }|D ]A}ti          |                    d:          d                   })|)|k    rt          ||	|)           B|D ]}*tA          j@                    }+tA          j3        ||*          |+_?        tA          jB        g t@          jC        d;          |+d;<   tA          jB        g t@          jC        d<          |+d<<   |D                    |+           t          |           t          |           t           j                            |d=          },|                    d>d?          }-t           j                            |-          st          jX        |-           t          |,|-||           t          jZ        |,           |	                    d@           | [                    |           | \                    |           |	                    dA|z             |	                    dB           d S )CNzBackup file not found.z!Please specify a target directorySAMBA_SELFTEST1zTarget directory is not emptyzServer name requiredetczsmb.confz.origz&Using %s as restored domain's smb.confprivatesam.ldbr   zAdding new DC to site '{0}' namingContextsr+  c                 ,    g | ]}t          |          S rb   )r6   ).0rs     rH   
<listcomp>z1cmd_domain_backup_restore.run.<locals>.<listcomp>  s    <<<!s1vv<<<r[   r   offline)rM   rL   r  forced_local_samdbnetbios_namez#Updating basic smb.conf settings...z"active directory domain controller)rL   
serverroler   r   zCreating account with SID: )specified_sidr-   
objectGUIDzshow_deleted:0zshow_recycled:0)r0   r/   r1   r2   r   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>dsServiceNamer1  zsecrets.ldb)r   rL   r   )domainr}   r  r  r   machinepasskey_version_numbersecure_channel_type	domaindns	forestdnsT)force)r@   pdcnaminginfrastructureschemaz*(&(objectClass=Server)(serverReference=*))r#  cnrepsFromrepsTor   rf   rK   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.)]re   rf   r   r   listdirenvironr   r   	getLoggerr   r   
addHandlerStreamHandlersysstdoutupperabspathrq   rr   
extractallrt   rg   r   copyfileget_loadparm_pathr4   r   r   LoadParmrP   r   r   r8   r   r2  r(  r$  r7   r9   rA  r   r   nc_listfull_nc_listdsdbUF_SERVER_TRUST_ACCOUNTUF_TRUSTED_FOR_DELEGATIONuserAccountControlr   domain_namer}   r   r6   join_add_objectsr   r   r<   ERR_CONSTRAINT_VIOLATIONr=   r:   schema_format_valuedecodeerrorr;   r   	ntds_guidr   r;  r   r  r   r   r  mynamedomsid	acct_passrW  r   SEC_CHAN_BDCr   dn_from_dns_nameforest_dns_nameseize_dns_role
seize_roler%  r   r   r   r   r	   remover!  r/  ).r   r   r   r   rh   newservernamer  r  r  r?   rv   smbconfcli_smbconfrL   private_dir
samdb_pathr>   r   rD   ncsrM   r   rB   rE   rF   rG   dup_resdup_edup_enum_
objectguidr   r|  secrets_pathsecrets_ldbr   	forest_dn	dns_rolesroler;   r   r`  r=  msgr   dest_sysvol_dirs.                                                 rH   r   zcmd_domain_backup_restore.run  s

     	9{ ; ; 	97888BCCCGNN9%% 	@"*Y*?*? 	@JNN+,,33>??? 	75666"$$&&&'/
;;<<< &++-- GOOI..	\+&&
i   



 ',,y%<<7!2333  1133 	2KK@;NOOOOK111[!!##
 gll9i88W\\+y99
*>3C3C24 4 4**511< ++E6::DKK5<<TBBCCC ll#."2!3  5 5<<s1vzz*:;;<<< )##&&uc222
 ((,,F%BT/4)68 8 8 "'*"D"'*"F#G 	9:::WmS_Y	b D	F 	F 	F 	F
 llum < <!$"1!2  4 4 !fjj))!,1CHH<===+	A  ws3xx/@/@ AAAA )	A )	A )	A6LT4s333G	,,CF5*s:J,K,K-0^.:^1A1B1D ' E E
     %
1s555 65555
 G!!22<7>qz,7OPQ7RT TJ#**733JLL + .99 : : : LL R S S SLL 3 4 4 4LL G       , !(
sssJJJ @ A A AG)	AV KMMveZ((&&	 /i0G030D0?A A/ 	Q
 (""""65"cm#*Hd< < < w||K??,^5E5E" # 68 8 8K"%)s}(+
cj(+/2/E040A	C 	C 	C 	C OO%%	*5+@+@+B+BCC	!9-!9-/	! 	O 	OHD"Syy##D%tT#NNN I 	5 	5DOOD%tO4444 Cll52244C<M&1  3 3 	- 	-AQUU4[[^$$B]""%,,,  
	 
	B+--CVE2&&CF!0141E1;= =C
O  .r/2/C/79 9CM LL 	'u---&u--- W\\)_==
&&22w~~o.. 	)K(((z?E7CCC
	* 	JKKK""5))) 	""5)))=	IJJJ & 	' 	' 	' 	' 	'sC   .0R   X+X	<TX
T5T0+X0T55CXX)NNNNNNNN)r   r   r   r   r   r   r6   r   r   r   r   r   r  r!  r(  r/  r2  rA  r   rb   r[   rH   r   r   2  s\        ,H 	%:EEE}#5C@@@ '<3GGG{;(	* 	* 	*|(L(	* 	* 	*x=CHHH	M ). 
@ @ @B# # #2    &  "  ( >BGK_' _' _' _' _' _'r[   r   c                   
   e Zd ZdZdZej        ej        dZ e	dde
           e	dde
           e	d	d
dd           e	dd
dd           e	dddddgd e            z            gZddgZd Zd Zd Zd Z	 	 	 ddZdS ) cmd_domain_backup_renamea  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                    |                                 }|                    |t          j        dgd          }|                                }|D ]}|d         D ]}	t          |	          }	|j        }
||	v rt          j        d|z  ||	          }|	                    d|d|
           t          j
                    }|
|_        t          j        |t          j        d          |d<   |                    |           |rS|	                    d|	d|
           t          j        |	t          j        d          |d<   |                    |           d	S )
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_dnr7   r8   SCOPE_ONELEVELr   r6   r;   resubr4   r   r   r   r   r,  )r   r?   r>   	old_realmdelete_old_dnspartitions_dnrD   	new_realmres_msgdns_rootr;   new_dns_rootr   s                rH   update_dns_rootz(cmd_domain_backup_rename.update_dns_root  s    //11llS5G"+&L  N N ))++	  	( 	(G#I. ( (x==Z((#%6%)*;Y*2$4 $4LKKK\\\22 NOOOAAD#&#5l696F6?$A $AAiL LLOOO & (XXXEGR%I J J J'*'9(:=:M:C(E (E) Q-(	( 	(r[   c                 t   |                                 }t          j        t          |                    }|                                }|                    |t          j        dgd|z            }|                    d|z             t          j                    }|d         j	        |_	        t          j
        |t          j        d          |d<   |                    |           d|d|}	|                    d|d         j	        d	|	           |                    |d         j	        |	d
g           dS )z>Renames the domain parition 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_basednr8   binary_encoder6   r  r7   r  r4   r   r;   r   r;  r   r1  )
r   r?   r>   new_netbios_namebase_dnnc_namer  rD   r   new_dns
             rH   rename_domain_partitionz0cmd_domain_backup_rename.rename_domain_partition  s8   
 **,,#CLL11//11llS5G"/&1G&;  = = 	A$% 	& 	& 	&KMM1vy-.>.1.B.;= =- 	Q  0//?CFIIIvv>???SVY)=====r[   c                 V   |                                 }d|d|}|                    d|z             |                    |dg           |                                                                }d|d|}|                    d|z             |                    |dg           d S )NzDC=z#,CN=MicrosoftDNS,DC=DomainDnsZones,zDeleting old DNS zone %sztree_delete:1z
DC=_msdcs.z#,CN=MicrosoftDNS,DC=ForestDnsZones,)r  r4   deleter   r   )r   r?   r>   r  basednr;   r  s          rH   delete_old_dns_zonesz-cmd_domain_backup_rename.delete_old_dns_zones+  s    ))++=FYYO.3444R/*+++((**99;;DMIIDLHN.3444R/*+++++r[   c                     |                                  t          |dddd          }t          |dd           d}d|g}|                    |           |                                 d	S )
z@Fixes attributes (i.e. objectCategory) that still use the old DNTFr  r  r  r  r.   r  Nr  )r   r>   r  r   r2   s        rH   fix_old_dn_attributesz.cmd_domain_backup_rename.fix_old_dn_attributes8  s     	!!!e4Tu%)+ + + 	?GGG-$n5H---  """""r[   Nc
                 V   |                                  }
|
                    t          j                   |                                }|                    |          }|t          d          t          |
|           | }|                                }|	                                }t          j        |          }|
                    d|z             |
                    d|z             |
                    d|z             t          j        |          }| }t          ||||
|||d|||	          }|j        }||k    r#t#          j        |           t          d          |j        }||k    r#t#          j        |           t          d	          |                                 |`|j        }t/          d
|z   |t1                      |          }t3          ||
          }t4          j                            |d          }t;          |||          }t=          |||                                           |                     |j!                   t/          |j"        t1                      |tF          j$                  }tK                      }tM          |d|           tM          |d|           tM          |d|           tM          |dd           | '                    |
|||           | (                    |
||           |r| )                    |
||           |
                    d           | *                    |           |rtW          |
|           tY          |||          }t[          ||d||d|d|d           t]          |
||           t#          j        |           d S )Nr   z"New realm for backed up domain: %sz$New base DN for backed up domain: %szNew domain NetBIOS name: %sr   r   )r?   rM   rL   r   r   rV   rh   r   z+Cannot use the current domain NetBIOS name.z(Cannot use the current domain DNS realm.r   r   r   r   r   r   r*  r   r1  z$Fixing DN attributes after rename...zOriginal domain r|   z (DNS realm))/r   r   r   INFOr   r   r   r   r   rj  r   r  r4   r   r   r   rv  r   r   r}   do_joinlocal_samdbr   r   r   rI   re   rf   rg   rZ   r   r5   rP   r  r>   r8   r   rc   r   r  r  r  r  r   rl   r   rw   )r   r  r  r   r   rV   rh   keep_dns_realmr   r   r?   rL   rM   r  new_base_dnru   r   r   
old_domainr  r   r   r   r   r   r>   rj   r   s                               rH   r   zcmd_domain_backup_rename.runF  s    ""%%%##%%((,, >0111	***++%++--)//11,];;8=HIII:[HIII1OCDDD!i000 ).%k?&3F,1b6E2B-3v4AC C C _
((M&!!!LMMMI	%%M&!!!IJJJ 	 O	 y61u(6(8(8RA A A
%j&99 W\\&/::
"62u55h
J,E,E,G,GHHH 	%+N4D4D24 4 4 !??%x888%':::%;;;%x888 	VUI~FFF 	$$VUODDD 	@%%feY???:;;;""5)))  	.vu--- &iIIHfoo#YYY0	1 	1 	1 	&&+666fr[   )NNNNFFN)r   r   r   r   r   r   r   r   r   r   r6   r   r   
takes_argsr  r  r  r  r   rb   r[   rH   r  r    se        8+H ).  	z 2===}#G	 	 	!,L	N 	N 	N~lEC	E 	E 	E xu~!#<#<#>#>?	@ 	@ 	@M $_5J#( #( #(N> > >4, , ,# # # =AGL,0g g g g g gr[   r  c                   p    e Zd ZdZdZdej        iZ edde	          gZ
dZd Zd	 Zd
 Zd Zd ZddZdS )cmd_domain_backup_offlinea  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                    || j         z   }	 t          ||d           nm# t          $ r`}	 t          j        |           nC# t
          $ r6}t          |d          r|j        t          j        k    r
Y d }~Y d }~d S |d }~ww xY w|d }~ww xY wt          j
                            |          s$d}t          |                    |                    d S )NT)readonlyerrnoz1tdbbackup said backup succeeded but {0} not found)
backup_extr$   r&   r   rr   	Exceptionhasattrr  EINVALre   rf   r   r   r$  )r   rf   backup_pathcopy_errrE   ss         rH   offline_tdb_copyz*cmd_domain_backup_offline.offline_tdb_copy  s    T_,	T;66666! 
	 
	 
	   1g&& 17el+B+BFFFFFFFFF N
	 w~~k** 	6CAqxx44555	6 	6s;    
B	?B
A?	%A:.B8A::A??BB	c                 6    t          ||| j        z              d S N)r%   r  )r   rf   s     rH   offline_mdb_copyz*cmd_domain_backup_offline.offline_mdb_copy  s    tdo-.....r[   c                 d   t           j                            |d          }t          |dz   |t          j                  }|                    d|z              |                                 |                     |dz              |                     |dz              |	                                 d S )Nsecrets.ldbrL   r   Starting transaction on .tdb)
re   rf   rg   r   r8   r   r4   r  r  transaction_cancel)r   r  rL   r?   r  secrets_objs         rH   backup_secretsz(cmd_domain_backup_offline.backup_secrets  s    w||K;;,/B # 68 8 8.=>>>%%'''lV3444lV3444&&(((((r[   c                 F   t           j                            |d          }d}|                    dt          j        |g          }||d         v o$t          |d         |         d                   dk    }d }	d }
|r1|                    d           | j        }
|	                                }	n3|                    d|z              | j
        }
|                                 |                    d	|z              | 
                    |           |d
z   }t          j        |          D ]}t           j                            ||          }|                    d          r$|                    d|z               |
|           [|                    d          r.|                    d|z              | 
                    |           |                    d|z              t          j        ||| j        z              t#          ||          }|r~	n|                                 |S )NrG  backendStorez
@PARTITIONr+  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 )re   rf   rg   r7   r8   r9   r6   r4   r  search_iteratorr  r  rc  endswithr   rm  r  rI   r  )r   r  r>   rL   r?   sam_ldb_pathstore_labelrD   mdb_backendres_iteratorcopy_function	sam_ldb_dsam_filerB   s                 rH   backup_smb_dbsz(cmd_domain_backup_offline.backup_smb_dbs  s:   w||K;; %llCN"-  0 0!SV+TCF;4G4J0K0Ku0T  	&KKKLLL 1M !0022LLKK2\ABBB 1M##%%%$|3444l+++ 4'	
9-- 
	F 
	FHw||Ix88H  (( F@8KLLLh''''""6** FBXMNNN%%h////=HIII(T_*DEEEE!%00 	'$$&&&
r[   c                 F   |j         |j        t          j                            |j                  d}fd|                                D             }|d         \  }}t          |          dk    rt          |d           \  }}|t          |          d          z  }|S )N)rF  staterE  c                 H    g | ]\  }}                     |          ||fS rb   )
startswith)rK  r  prf   s      rH   rM  z:cmd_domain_backup_offline.get_arc_path.<locals>.<listcomp>1  sA     - - -FQ++-!Q - - -r[   r   r   c                 ,    t          | d                   S )Nr   )r:   )r  s    rH   <lambda>z8cmd_domain_backup_offline.get_arc_path.<locals>.<lambda>8  s    QqT r[   )key)	r  	state_dirre   rf   dirnamer  itemsr:   max)r   rf   
conf_pathsbackup_dirsmatching_dirsarc_pathfs_paths    `     rH   get_arc_pathz&cmd_domain_backup_offline.get_arc_path-  s    ","8 * 4 gooj.@AAC C- - - -k.?.?.A.A - - -)!,' }!! #M7J7J K K KHgDW''r[   Nc           	      T   t          j                    }|                    t           j                   |                    t          j        t          j                             |                                }t          j
                            ||                    d                    }|j        r$t          j                            |j                  s<|                    d                    |j                             t'          d          t)          ||           |j        |j        t          j                            |j                  g}|                    d                    d                    |                               g }t7                      }|D ]}	t          j        |	          D ]f\  }
}}|
                    |j                  r"|
                    d          sd|
v r<|
                    t          j                            |j         d                    ru|D ]}t          j                            |
|          }	 t          j!        |d	
          }n(# tD          $ r |#                    | d           Y ^w xY w|j$        |j%        f|v rs|                    | j&                  rt          j'        |           |                    d          r|(                    |           |)                    |j$        |j%        f           htU          |j        tW                      |tX          j-                  }| .                    |j        ||           | /                    |j        |||          }|0                                }tc          j2        |          }d }tg          |j        | j&        z   tW                      |dgtX          j-                  }ti                      }tk          |d|           tk          |d|           tk          |dd           d }|D ]}t          j                            || j&        z             s|                    d          r|                    d|z              tg          ||tX          j-                  }|6                                 |                    d           | 7                    |           |8                                 |                    d          r-|                    d|z              | 7                    |           
ts          j:        |d          }t          j                            |d          }tw          j<        |d          }|                    d           d}t          j                            ||          }t{          |j        ||j        |           |)                    ||           t          j'        |           t}          ||ddd            t          j                            |d!          }|)                    |t          j        ?                    |                     t          j'        |           |                    d"           |D ]}| @                    ||          }t          j                            || j&        z             r_|                    d#|z   | j&        z   d$z              |)                    || j&        z   |%           t          j'        || j&        z              |                    d          s|                    d          r|                    d&|z              |                    d'|z              |)                    ||%           |A                                 t          jB        |t          j                            |d(                    |                               t          jC        |           |                    d)           d S )*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   rL   r   r   r   r   r   rN  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.bz2rn   z&running offline ntacl backup of sysvolr   	localhostTry   zbuilding backup tarz   adding backup z to tar and deleting filero   z   skipping z   adding misc file zsamba-backup-{0}.tar.bz2zBackup succeeded.)Dr   re  r   r   rf  rg  rh  ri  r   r   	provisionprovision_paths_from_lpr   r>   re   rf   r   r{  r$  r   r   r  r  r  r  r4   rg   setwalkr  rK   r  binddns_dirstatFileNotFoundErrorwarningst_inost_devr  r  appendrs   r   r   r8   r   r  r  r5   r   r   r   rc   r   r  r  r  r   r   rq   rr   r
   r   basenamer  rt   r1  rmdir)r   r   rh   r?   rL   r   r  	all_files	all_stats
backup_dirworking_dirr  	filenamesrk   	full_pathr  r>   rB   dom_sid_strr   rj   rf   ldb_objtemp_tar_dirtemp_tar_nametarsysvol_tar_fnr   	backup_fnr  s                                 rH   r   zcmd_domain_backup_offline.run=  s   "$$&&&'/
;;<<< ##%%77BFF7OOLL 	Gu{ ; ; 	GLL3::5;GGHHH  F G G G 		*** (%/wu}557188+9N9NOOPPP 	EE	% %	8 %	8J/1wz/B/B $8 $8+a))%,77 ''00 H4K4K ))"',,u7H%*P*PQQ  ) 8 8H "[( C CI
!GIuEEE, ! ! !)'E'E'EFFF ! !(+y88   ((99 !	),,,   ((11 ! $$Y///MM18QX"6777758$8R %+N4D4D24 4 4 	E-r6:::!!%"3UBGG **,,";//
  do5#1#3#3)l#2HJ J J !??%x888%#666%y999   	0 	0D7>>$"899 
0==(( 	0KK Cd JKKK!$2S5KLLLG--///KK GHHH))$///..0000]]6** 0KK E LMMM))$///  'I/JL L L\3IJJl='22<==='W\\,>>
u|ZHHH
M***
	*b)[$GGGGLL|<<		27++I66777
	))*** 	0 	0D((u55Hw~~dT_455 	0/(:T_L78 9 9 9t.AAA	$01111v&& 0$--*?*? 0NX566662X=>>>h////		
	-',,y9@@JJL L	M 	M 	M 	'(((((s   I(("J	J	)NN)r   r   r   r   r   r   r   r   r   r6   r   r  r  r  r  r  r  r   rb   r[   rH   r  r    s        @ @ !HW)
 	}1	 	 	M  J6 6 6&/ / /
) ) )8 8 8v   ]) ]) ]) ]) ]) ])r[   r  c                   `    e Zd ZdZ e             e             e             e            dZdS )cmd_domain_backupz)Create or restore a backup of the domain.)rN  r   r1  restoreN)	r   r   r   r   r  r   r  r   subcommandsrb   r[   rH   r  r    sP        337799557755777799; ;KKKr[   r  r  )]r^   re   rh  rq   r   r   r   r   r   samba.getoptgetoptr   samba.samdbr   r   r8   r   samba.samba3r   rT   r   rN   samba.ntaclsr   r	   r
   
samba.authr   
samba.joinr   r   r   samba.dcerpc.securityr   samba.netcmdr   r   samba.dcerpcr   r   r   r   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*   rI   rZ   rc   rl   rw   r   r   r   r   netcmdCommandr   r   r  r  SuperCommandr  rb   r[   rH   <module>r9     si  $  				 



      



       8 8 8 8 8 8 8 8 



       8 8 8 8 8 8 ) ) ) ) ) ) F F F F F F F F F F % % % % % % I I I I I I I I I I ) ) ) ) ) ) - - - - - - - - 1 1 1 1 1 1 1 1 1 1       ! ! ! ! ! ! 5 5 5 5 5 5 5 5 ? ? ? ? ? ? % % % % % % / / / / / / # # # # # # 				 N N N N N N N N N N6 6 6 6 6 6 6 6 6 6 $ # # # # # # # # # # #  ) ) ) ) ) )       ( ( ( ( ( (       2 2 2 2 2 2-% -% -%`  A A A- - -
    $   ,  @ @ @) ) ),_" _" _" _" _"u|3 _" _" _"DA' A' A' A' A' A' A' A'Hw w w w wu|3 w w wtj) j) j) j) j) 4 j) j) j)Z	; ; ; ; ;1 ; ; ; ; ;r[   