AutomatedLabHybrid.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
function Connect-Lab
{
    #.ExternalHelp AutomatedLab.help.xml
    [CmdletBinding(DefaultParameterSetName = 'Lab2Lab')]
    param
    (
        [Parameter(Mandatory = $true, Position = 0)]
        [System.String]
        $SourceLab,

        [Parameter(Mandatory = $true, ParameterSetName = 'Lab2Lab', Position = 1)]
        [System.String]
        $DestinationLab,

        [Parameter(Mandatory = $true, ParameterSetName = 'Site2Site', Position = 1)]
        [System.String]
        $DestinationIpAddress,

        [Parameter(Mandatory = $true, ParameterSetName = 'Site2Site', Position = 2)]
        [System.String]
        $PreSharedKey,

        [Parameter(ParameterSetName = 'Site2Site', Position = 3)]
        [System.String[]]
        $AddressSpace,

        [Parameter(Mandatory = $false)]
        [System.String]
        $NetworkAdapterName = 'Ethernet'
    )

    Write-LogFunctionEntry

    if ((Get-Lab -List) -notcontains $SourceLab)
    {
        throw "Source lab $SourceLab does not exist."
    }

    if ($DestinationIpAddress)
    {
        Write-Verbose -Message ('Connecting {0} to {1}' -f $SourceLab, $DestinationIpAddress)
        Connect-OnPremisesWithEndpoint -LabName $SourceLab -IPAddress $DestinationIpAddress -AddressSpace $AddressSpace -Psk $PreSharedKey
        return
    }

    if ((Get-Lab -List) -notcontains $DestinationLab)
    {
        throw "Destination lab $DestinationLab does not exist."
    }

    $sourceFolder = '{0}\AutomatedLab-Labs\{1}' -f [System.Environment]::GetFolderPath('MyDocuments'), $SourceLab
    $sourceFile = Join-Path -Path $sourceFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
    if (-not $sourceFile)
    {
        throw "Lab.xml is missing for $SourceLab"
    }
    
    $destinationFolder = '{0}\AutomatedLab-Labs\{1}' -f [System.Environment]::GetFolderPath('MyDocuments'), $DestinationLab
    $destinationFile = Join-Path -Path $destinationFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
    if (-not $destinationFile)
    {
        throw "Lab.xml is missing for $DestinationLab"
    }    

    $sourceHypervisor = ([xml](Get-Content $sourceFile)).Lab.DefaultVirtualizationEngine
    $sourceRoutedAddressSpaces = ([xml](Get-Content $sourceFile)).Lab.VirtualNetworks.VirtualNetwork.AddressSpace | ForEach-Object { 
        if (-not [System.String]::IsNullOrWhiteSpace($_.IpAddress.AddressAsString))
        {
            "$($_.IpAddress.AddressAsString)/$($_.SerializationCidr)" 
        }
    }
    
    $destinationHypervisor = ([xml](Get-Content $destinationFile)).Lab.DefaultVirtualizationEngine
    $destinationRoutedAddressSpaces = ([xml](Get-Content $destinationFile)).Lab.VirtualNetworks.VirtualNetwork.AddressSpace | ForEach-Object { 
        if (-not [System.String]::IsNullOrWhiteSpace($_.IpAddress.AddressAsString))
        {
            "$($_.IpAddress.AddressAsString)/$($_.SerializationCidr)" 
        }
    }
    
    Write-Verbose -Message ('Source Hypervisor: {0}, Destination Hypervisor: {1}' -f $sourceHypervisor, $destinationHypervisor)

    if (-not ($sourceHypervisor -eq 'Azure' -or $destinationHypervisor -eq 'Azure'))
    {
        throw 'On-premises to on-premises connections are currently not implemented. One or both labs need to be Azure'
    }

    if ($sourceHypervisor -eq 'Azure')
    {        
        $connectionParameters = @{
            SourceLab           = $SourceLab
            DestinationLab      = $DestinationLab
            AzureAddressSpaces  = $sourceRoutedAddressSpaces
            OnPremAddressSpaces = $destinationRoutedAddressSpaces
        }
    }
    else 
    {
        $connectionParameters = @{
            SourceLab           = $DestinationLab
            DestinationLab      = $SourceLab
            AzureAddressSpaces  = $destinationRoutedAddressSpaces
            OnPremAddressSpaces = $sourceRoutedAddressSpaces
        }
    }

    if ($sourceHypervisor -eq 'Azure' -and $destinationHypervisor -eq 'Azure')
    {
        Write-Verbose -Message ('Connecting Azure lab {0} to Azure lab {1}' -f $SourceLab, $DestinationLab)
        Connect-AzureLab -SourceLab $SourceLab -DestinationLab $DestinationLab
        return
    }
    
    Write-Verbose -Message ('Connecting on-premises lab to Azure lab. Source: {0} <-> Destination {1}' -f $SourceLab, $DestinationLab)
    Connect-OnPremisesWithAzure @connectionParameters

    Write-LogFunctionExit
}

function Disconnect-Lab
{
    #.ExternalHelp AutomatedLab.help.xml
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        $SourceLab,

        [Parameter(Mandatory)]
        $DestinationLab
    )

    Write-LogFunctionEntry

    foreach ($LabName in @($SourceLab, $DestinationLab))
    {
        Import-Lab -Name $LabName -ErrorAction Stop -NoValidation
        $lab = Get-Lab

        Invoke-LabCommand -ActivityName 'Remove conditional forwarders' -ComputerName (Get-LabMachine -Role RootDC) -ScriptBlock {
            Get-DnsServerZone | Where-Object -Property ZoneType -EQ Forwarder | Remove-DnsServerZone -Force
        }

        if ($lab.DefaultVirtualizationEngine -eq 'Azure')
        {            
            $resourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
         
            Write-Verbose -Message ('Removing VPN resources in Azure lab {0}, Resource group {1}' -f $lab.Name, $resourceGroupName)
            
            $connection = Get-AzureRmVirtualNetworkGatewayConnection -Name s2sconnection -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
            $gw = Get-AzureRmVirtualNetworkGateway -Name s2sgw -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
            $localgw = Get-AzureRmLocalNetworkGateway -Name onpremgw -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
            $ip = Get-AzureRmPublicIpAddress -Name s2sip -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue

            if ($connection)
            {
                $connection | Remove-AzureRmVirtualNetworkGatewayConnection -Force
            }

            if ($gw)
            {
                $gw | Remove-AzureRmVirtualNetworkGateway -Force
            }

            if ($ip)
            {
                $ip | Remove-AzureRmPublicIpAddress -Force
            }
            
            if ($localgw)
            {
                $localgw | Remove-AzureRmLocalNetworkGateway -Force
            }
        }
        else
        {            
            $router = Get-LabVm -Role Routing -ErrorAction SilentlyContinue

            if (-not $router)
            {
                # How did this even work...
                continue
            }

            Write-Verbose -Message ('Disabling S2SVPN in on-prem lab {0} on router {1}' -f $lab.Name, $router.Name)

            Invoke-LabCommand -ActivityName "Disabling S2S on $($router.Name)" -ComputerName $router -ScriptBlock {
                Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue | Remove-VpnS2SInterface -Force -ErrorAction SilentlyContinue
                Uninstall-RemoteAccess -VpnType VPNS2S -Force -ErrorAction SilentlyContinue
            }
        }
    }

    Write-LogFunctionExit
}

function Restore-LabConnection
{
    #.ExternalHelp AutomatedLab.help.xml
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $SourceLab,

        [Parameter(Mandatory = $true)]
        [System.String]
        $DestinationLab
    )

    if ((Get-Lab -List) -notcontains $SourceLab)
    {
        throw "Source lab $SourceLab does not exist."
    }

    if ((Get-Lab -List) -notcontains $DestinationLab)
    {
        throw "Destination lab $DestinationLab does not exist."
    }

    $sourceFolder = '{0}\AutomatedLab-Labs\{1}' -f [System.Environment]::GetFolderPath('MyDocuments'), $SourceLab
    $sourceFile = Join-Path -Path $sourceFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
    if (-not $sourceFile)
    {
        throw "Lab.xml is missing for $SourceLab"
    }
    
    $destinationFolder = '{0}\AutomatedLab-Labs\{1}' -f [System.Environment]::GetFolderPath('MyDocuments'), $DestinationLab
    $destinationFile = Join-Path -Path $destinationFolder -ChildPath Lab.xml -Resolve -ErrorAction SilentlyContinue
    if (-not $destinationFile)
    {
        throw "Lab.xml is missing for $DestinationLab"
    }  

    $sourceHypervisor = ([xml](Get-Content $sourceFile)).Lab.DefaultVirtualizationEngine
    $destinationHypervisor = ([xml](Get-Content $destinationFile)).Lab.DefaultVirtualizationEngine

    if ($sourceHypervisor -eq 'Azure')
    {
        $source = $SourceLab
        $destination = $DestinationLab
    }
    else
    {
        $source = $DestinationLab
        $destination = $SourceLab
    }

    Write-Verbose -Message "Checking Azure lab $source"
    Import-Lab -Name $source -NoValidation
    $resourceGroup = (Get-LabAzureDefaultResourceGroup).ResourceGroupName

    $localGateway = Get-AzureRmLocalNetworkGateway -Name onpremgw -ResourceGroupName $resourceGroup -ErrorAction Stop
    $vpnGatewayIp = Get-AzureRmPublicIpAddress -Name s2sip -ResourceGroupName $resourceGroup -ErrorAction Stop

    try
    {
        $labIp = Get-PublicIpAddress -ErrorAction Stop
    }
    catch
    {
        Write-Warning -Message 'Public IP address could not be determined. Reconnect-Lab will probably not work.'
    }

    if ($localGateway.GatewayIpAddress -ne $labIp)
    {
        Write-Verbose -Message "Gateway address $($localGateway.GatewayIpAddress) does not match local IP $labIP and will be changed"
        $localGateway.GatewayIpAddress = $labIp
        [void] ($localGateway | Set-AzureRmLocalNetworkGateway)
    }

    Import-Lab -Name $destination -NoValidation
    $router = Get-LabVm -Role Routing

    Invoke-LabCommand -ActivityName 'Checking S2S connection' -ComputerName $router -ScriptBlock {
        param
        (
            [System.String]
            $azureDestination
        )
    
        $s2sConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction Stop -Verbose
        
        if ($s2sConnection.Destination -notcontains $azureDestination)
        {
            $s2sConnection.Destination += $azureDestination
            $s2sConnection | Set-VpnS2SInterface -Verbose
        }
    } -ArgumentList @($vpnGatewayIp.IpAddress)
}

function Initialize-GatewayNetwork
{
    param
    (
        [Parameter(Mandatory = $true)]
        [AutomatedLab.Lab]
        $Lab
    )
    
    Write-LogFunctionEntry
    Write-Verbose -Message ('Creating gateway subnet for lab {0}' -f $Lab.Name)

    $targetNetwork = $Lab.VirtualNetworks | Select-Object -First 1
    $sourceMask = $targetNetwork.AddressSpace.Cidr
    $sourceMaskIp = $targetNetwork.AddressSpace.NetMask
    $superNetMask = $sourceMask - 1
    $superNetIp = $targetNetwork.AddressSpace.IpAddress.AddressAsString
    
    $gatewayNetworkAddressFound = $false
    $incrementedIp = $targetNetwork.AddressSpace.IPAddress.Increment()
    $decrementedIp = $targetNetwork.AddressSpace.IPAddress.Decrement()
    $isDecrementing = $false
    
    while (-not $gatewayNetworkAddressFound)
    {
        if (-not $isDecrementing)
        {
            $incrementedIp = $incrementedIp.Increment()
            $tempNetworkAdress = Get-NetworkAddress -IPAddress $incrementedIp.AddressAsString -SubnetMask $sourceMaskIp.AddressAsString
    
            if ($tempNetworkAdress -eq $targetNetwork.AddressSpace.Network.AddressAsString)
            {
                continue
            }
    
            $gatewayNetworkAddress = $tempNetworkAdress
    
            if ($gatewayNetworkAddress -in (Get-NetworkRange -IPAddress $targetnetwork.AddressSpace.Network.AddressAsString -SubnetMask $superNetMask))
            {
                $gatewayNetworkAddressFound = $true
            }
            else
            {
                $isDecrementing = $true
            }
        }
    
        $decrementedIp = $decrementedIp.Decrement()
        $tempNetworkAdress = Get-NetworkAddress -IPAddress $decrementedIp.AddressAsString -SubnetMask $sourceMaskIp.AddressAsString
    
        if ($tempNetworkAdress -eq $targetNetwork.AddressSpace.Network.AddressAsString)
        {
            continue
        }
    
        $gatewayNetworkAddress = $tempNetworkAdress
    
        if (([AutomatedLab.IPAddress]$gatewayNetworkAddress).Increment().AddressAsString -in (Get-NetworkRange -IPAddress $targetnetwork.AddressSpace.Network.AddressAsString -SubnetMask $superNetMask))
        {
            $gatewayNetworkAddressFound = $true
        }
    }
    
    Write-Verbose -Message ('Calculated supernet: {0}, extending Azure VNet and creating gateway subnet {1}' -f "$($superNetIp)/$($superNetMask)", "$($gatewayNetworkAddress)/$($sourceMask)")
    $vNet = Get-LWAzureNetworkSwitch -virtualNetwork $targetNetwork
    $vnet.AddressSpace.AddressPrefixes[0] = "$($superNetIp)/$($superNetMask)"
    $gatewaySubnet = Get-AzureRmVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $vnet -ErrorAction SilentlyContinue
        
    if (-not $gatewaySubnet)
    {
        $vnet | Add-AzureRmVirtualNetworkSubnetConfig -Name GatewaySubnet -AddressPrefix "$($gatewayNetworkAddress)/$($sourceMask)"
        $vnet = $vnet | Set-AzureRmVirtualNetwork -ErrorAction Stop
    }    
    
    $vnet = (Get-LWAzureNetworkSwitch -VirtualNetwork $targetNetwork | Where-Object -Property ID)[0]
    Write-LogFunctionExit

    return $vnet
}

function Connect-OnPremisesWithAzure
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $SourceLab,
        [Parameter(Mandatory = $true)]
        [System.String]
        $DestinationLab,
        [Parameter(Mandatory = $true)]
        [System.String[]]
        $AzureAddressSpaces,
        [Parameter(Mandatory = $true)]
        [System.String[]]
        $OnPremAddressSpaces
    )

    Write-LogFunctionEntry
    Import-Lab $SourceLab -NoValidation
    $lab = Get-Lab
    $sourceResourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
    $sourceLocation = Get-LabAzureDefaultLocation
    $sourceDcs = Get-LabMachine -Role DC, RootDC, FirstChildDC

    $vnet = Initialize-GatewayNetwork -Lab $lab
    
    $labPublicIp = Get-PublicIpAddress

    if (-not $labPublicIp)
    {
        throw 'No public IP for hypervisor found. Make sure you are connected to the internet.'
    }

    Write-Verbose -Message "Found Hypervisor host public IP of $labPublicIp"
    
    $genericParameters = @{
        ResourceGroupName = $sourceResourceGroupName
        Location          = $sourceLocation
    }
    
    $publicIpParameters = $genericParameters.Clone()
    $publicIpParameters.Add('Name', 's2sip')
    $publicIpParameters.Add('AllocationMethod', 'Dynamic')
    $publicIpParameters.Add('IpAddressVersion', 'IPv4')
    $publicIpParameters.Add('DomainNameLabel', "$($lab.name)-s2s".ToLower())
    $publicIpParameters.Add('Force', $true)
    
    $gatewaySubnet = Get-AzureRmVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $vnet -ErrorAction SilentlyContinue
    $gatewayPublicIp = New-AzureRmPublicIpAddress @publicIpParameters -WarningAction SilentlyContinue 
    $gatewayIpConfiguration = New-AzureRmVirtualNetworkGatewayIpConfig -Name gwipconfig -SubnetId $gatewaySubnet.Id -PublicIpAddressId $gatewayPublicIp.Id -WarningAction SilentlyContinue
    
    $remoteGatewayParameters = $genericParameters.Clone()
    $remoteGatewayParameters.Add('Name', 's2sgw')
    $remoteGatewayParameters.Add('GatewayType', 'Vpn')
    $remoteGatewayParameters.Add('VpnType', 'RouteBased')
    $remoteGatewayParameters.Add('GatewaySku', 'VpnGw1')
    $remoteGatewayParameters.Add('IpConfigurations', $gatewayIpConfiguration)
    $remoteGatewayParameters.Add('Force', $true)
    
    $onPremGatewayParameters = $genericParameters.Clone()
    $onPremGatewayParameters.Add('Name', 'onpremgw')
    $onPremGatewayParameters.Add('GatewayIpAddress', $labPublicIp)
    $onPremGatewayParameters.Add('AddressPrefix', $onPremAddressSpaces)
    $onPremGatewayParameters.Add('Force', $true)
        
    # Gateway creation
    $gw = Get-AzureRmVirtualNetworkGateway -Name s2sgw -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue
    if (-not $gw)
    {
        Write-ScreenInfo -TaskStart -Message 'Creating Azure Virtual Network Gateway - this will take some time.'
        $gw = New-AzureRmVirtualNetworkGateway @remoteGatewayParameters -WarningAction SilentlyContinue
        Write-ScreenInfo -TaskEnd -Message 'Virtual Network Gateway created.'
    }
    
    $onPremisesGw = Get-AzureRmLocalNetworkGateway -Name onpremgw -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue
    if (-not $onPremisesGw -or $onPremisesGw.GatewayIpAddress -ne $labPublicIp)
    {
        $onPremisesGw = New-AzureRmLocalNetworkGateway @onPremGatewayParameters -WarningAction SilentlyContinue
    }
    
    # Connection creation
    $connectionParameters = $genericParameters.Clone()
    $connectionParameters.Add('Name', 's2sconnection')
    $connectionParameters.Add('ConnectionType', 'IPsec')
    $connectionParameters.Add('SharedKey', 'Somepass1')
    $connectionParameters.Add('EnableBgp', $false)
    $connectionParameters.Add('Force', $true)
    $connectionParameters.Add('VirtualNetworkGateway1', $gw)
    $connectionParameters.Add('LocalNetworkGateway2', $onPremisesGw)
        
    $conn = New-AzureRmVirtualNetworkGatewayConnection @connectionParameters -WarningAction SilentlyContinue
    
    # Step 3: Import the HyperV lab and install a Router if not already present
    Import-Lab $DestinationLab -NoValidation    
    
    $lab = Get-Lab
    $router = Get-LabVm -Role Routing -ErrorAction SilentlyContinue
    $destinationDcs = Get-LabMachine -Role DC, RootDC, FirstChildDC
    $gatewayPublicIp = Get-AzureRmPublicIpAddress -Name s2sip -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue

    if (-not $gatewayPublicIp -or $gatewayPublicIp.IpAddress -notmatch '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
    {
        throw 'Public IP has either not been created or is currently unassigned.'
    }
    
    if (-not $router)
    {
        throw @'
        No router in your lab. Please redeploy your lab after adding e.g. the following lines:
        Add-LabVirtualNetworkDefinition -Name External -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' }
        $netAdapter = @()
        $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName
        $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch External -UseDhcp
        $machineName = "ALS2SVPN$((1..7 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')"
        Add-LabMachineDefinition -Name $machineName -Roles Routing -NetworkAdapter $netAdapter -OperatingSystem 'Windows Server 2016 SERVERDATACENTER'
'@

    }
    
    # Step 4: Configure S2S VPN Connection on Router
    $externalAdapters = $router.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' }
        
    if ($externalAdapters.Count -ne 1)
    {
        throw "Automatic configuration of VPN gateway can only be done if there is exactly 1 network adapter connected to an external network switch. The machine '$machine' knows about $($externalAdapters.Count) externally connected adapters"
    }
    
    if ($externalAdapters)
    {
        $mac = $externalAdapters | Select-Object -ExpandProperty MacAddress
        $mac = ($mac | Get-StringSection -SectionSize 2) -join ':'

        if (-not $mac)
        {
            throw ('Get-LabVm returned an empty MAC address for {0}. Cannot continue' -f $router.Name)
        }
    }
    
    $scriptBlock = {
        param
        (
            $AzureDnsEntry,
            $RemoteAddressSpaces,
            $MacAddress
        )
        
        $externalAdapter = Get-WmiObject -Class Win32_NetworkAdapter -Filter ('MACAddress = "{0}"' -f $MacAddress) |
            Select-Object -ExpandProperty NetConnectionID
        
        Set-Service -Name RemoteAccess -StartupType Automatic
        Start-Service -Name RemoteAccess -ErrorAction SilentlyContinue
        
        $null = netsh.exe routing ip nat install
        $null = netsh.exe routing ip nat add interface $externalAdapter
        $null = netsh.exe routing ip nat set interface $externalAdapter mode=full

        $status = Get-RemoteAccess -ErrorAction SilentlyContinue
        if (($status.VpnStatus -ne 'Uninstalled') -or ($status.DAStatus -ne 'Uninstalled') -or ($status.SstpProxyStatus -ne 'Uninstalled'))
        {
            Uninstall-RemoteAccess -Force
        }

        if ($status.VpnS2SStatus -ne 'Installed' -or $status.RoutingStatus -ne 'Installed')
        {
            Install-RemoteAccess -VpnType VPNS2S -ErrorAction Stop        
        }
        
        try
        {
            # Try/Catch to catch exception while we have to wait for Install-RemoteAccess to finish up
            Start-Service RemoteAccess -ErrorAction SilentlyContinue
            $azureConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue
        }
        catch
        {
            # If Get-VpnS2SInterface throws HRESULT 800703bc, wait even longer
            Start-Sleep -Seconds 120
            Start-Service RemoteAccess -ErrorAction SilentlyContinue
            $azureConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue
        }
        
    
        if (-not $azureConnection)
        {
            $parameters = @{
                Name                 = 'AzureS2S'
                Protocol             = 'IKEv2'
                Destination          = $AzureDnsEntry
                AuthenticationMethod = 'PskOnly'
                SharedSecret         = 'Somepass1'
                NumberOfTries        = 0
                Persistent           = $true
                PassThru             = $true
            }
            $azureConnection = Add-VpnS2SInterface @parameters
        }        
    
        $count = 1

        while ($count -le 3)
        {
            try
            {
                $azureConnection | Connect-VpnS2SInterface -ErrorAction Stop
                $connectionEstablished = $true
            }
            catch
            {
                Write-Warning -Message "Could not connect to $AzureDnsEntry ($count/3)"
                $connectionEstablished = $false
            }

            $count++
        }

        if (-not $connectionEstablished)
        {
            throw "Error establishing connection to $AzureDnsEntry after 3 tries. Check your NAT settings, internet connectivity and Azure resource group"
        }
        
        $null = netsh.exe ras set conf confstate = enabled        
        $null = netsh.exe routing ip dnsproxy install


        $dialupInterfaceIndex = (Get-NetIPInterface -AddressFamily IPv4 | Where-Object -Property InterfaceAlias -eq 'AzureS2S').ifIndex
    
        if (-not $dialupInterfaceIndex)
        {
            throw "Connection to $AzureDnsEntry has not been established. Cannot add routes to $($addressSpace -join ',')."
        }
        
        foreach ($addressSpace in $RemoteAddressSpaces)
        {
            $null = New-NetRoute -DestinationPrefix $addressSpace -InterfaceIndex $dialupInterfaceIndex -AddressFamily IPv4 -NextHop 0.0.0.0 -RouteMetric 1
        }
    }
    
    Invoke-LabCommand -ActivityName 'Enabling S2S VPN functionality and configuring S2S VPN connection' `
        -ComputerName $router `
        -ScriptBlock $scriptBlock `
        -ArgumentList @($gatewayPublicIp.IpAddress, $AzureAddressSpaces, $mac) `
        -Retries 3 -RetryIntervalInSeconds 10

    # Configure DNS forwarding
    Set-VpnDnsForwarders -SourceLab $SourceLab -DestinationLab $DestinationLab
        
    Write-LogFunctionExit
}

function Connect-OnPremisesWithEndpoint
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $LabName,
        [Parameter(Mandatory = $true)]
        [System.String]
        $DestinationHost,
        [Parameter(Mandatory = $true)]
        [System.String[]]
        $AddressSpace,
        [Parameter(Mandatory = $true)]
        [System.String]
        $Psk
    )

    Write-LogFunctionEntry
    Import-Lab $LabName -NoValidation    
    
    $lab = Get-Lab
    $router = Get-LabVm -Role Routing -ErrorAction SilentlyContinue
    
    if (-not $router)
    {
        throw @'
        No router in your lab. Please redeploy your lab after adding e.g. the following lines:
        Add-LabVirtualNetworkDefinition -Name External -HyperVProperties @{ SwitchType = 'External'; AdapterName = 'Wi-Fi' }
        $netAdapter = @()
        $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch $labName
        $netAdapter += New-LabNetworkAdapterDefinition -VirtualSwitch External -UseDhcp
        $machineName = "ALS2SVPN$((1..7 | ForEach-Object { [char[]](97..122) | Get-Random }) -join '')"
        Add-LabMachineDefinition -Name $machineName -Roles Routing -NetworkAdapter $netAdapter -OperatingSystem 'Windows Server 2016 SERVERDATACENTER'
'@

    }
    
    $externalAdapters = $router.NetworkAdapters | Where-Object { $_.VirtualSwitch.SwitchType -eq 'External' }
        
    if ($externalAdapters.Count -ne 1)
    {
        throw "Automatic configuration of VPN gateway can only be done if there is exactly 1 network adapter connected to an external network switch. The machine '$machine' knows about $($externalAdapters.Count) externally connected adapters"
    }
    
    $externalAdapter = $externalAdapters[0]
    $mac = $externalAdapter.MacAddress
    $mac = ($mac | Get-StringSection -SectionSize 2) -join '-'
    
    $scriptBlock = {
        param
        (
            $DestinationHost,
            $RemoteAddressSpaces
        )
            
        $status = Get-RemoteAccess -ErrorAction SilentlyContinue
        if ($status.VpnS2SStatus -ne 'Installed' -or $status.RoutingStatus -ne 'Installed')
        {
            Install-RemoteAccess -VpnType VPNS2S -ErrorAction Stop        
        }
        
        Restart-Service -Name RemoteAccess
    
        $remoteConnection = Get-VpnS2SInterface -Name AzureS2S -ErrorAction SilentlyContinue
    
        if (-not $remoteConnection)
        {
            $parameters = @{
                Name                 = 'ALS2S'
                Protocol             = 'IKEv2'
                Destination          = $DestinationHost
                AuthenticationMethod = 'PskOnly'
                SharedSecret         = 'Somepass1'
                NumberOfTries        = 0
                Persistent           = $true
                PassThru             = $true
            }
            $remoteConnection = Add-VpnS2SInterface @parameters
        }        
    
        $remoteConnection | Connect-VpnS2SInterface -ErrorAction Stop
    
        $dialupInterfaceIndex = (Get-NetIPInterface | Where-Object -Property InterfaceAlias -eq 'ALS2S').ifIndex
    
        foreach ($addressSpace in $RemoteAddressSpaces)
        {
            New-NetRoute -DestinationPrefix $addressSpace -InterfaceIndex $dialupInterfaceIndex -AddressFamily IPv4 -NextHop 0.0.0.0 -RouteMetric 1
        }
    }
    
    Invoke-LabCommand -ActivityName 'Enabling S2S VPN functionality and configuring S2S VPN connection' `
        -ComputerName $router `
        -ScriptBlock $scriptBlock `
        -ArgumentList @($DestinationHost, $AddressSpace) `
        -Retries 3 -RetryIntervalInSeconds 10

    Write-LogFunctionExit
}

function Connect-AzureLab
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $SourceLab,
        [Parameter(Mandatory = $true)]
        [System.String]
        $DestinationLab
    )

    Write-LogFunctionEntry
    Import-Lab $SourceLab -NoValidation
    $lab = Get-Lab
    $sourceResourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
    $sourceLocation = Get-LabAzureDefaultLocation
    $sourceVnet = Initialize-GatewayNetwork -Lab $lab
    
    Import-Lab $DestinationLab -NoValidation
    $lab = Get-Lab
    $destinationResourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
    $destinationLocation = Get-LabAzureDefaultLocation
    $destinationVnet = Initialize-GatewayNetwork -Lab $lab
    
    $sourcePublicIpParameters = @{
        ResourceGroupName = $sourceResourceGroupName
        Location          = $sourceLocation
        Name              = 's2sip'
        AllocationMethod  = 'Dynamic'
        IpAddressVersion  = 'IPv4'
        DomainNameLabel   = "$($SourceLab)-s2s".ToLower()
        Force             = $true
    }

    $destinationPublicIpParameters = @{
        ResourceGroupName = $destinationResourceGroupName
        Location          = $destinationLocation
        Name              = 's2sip'
        AllocationMethod  = 'Dynamic'
        IpAddressVersion  = 'IPv4'
        DomainNameLabel   = "$($DestinationLab)-s2s".ToLower()
        Force             = $true
    }   
    
    $sourceGatewaySubnet = Get-AzureRmVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $sourceVnet -ErrorAction SilentlyContinue
    $sourcePublicIp = New-AzureRmPublicIpAddress @sourcePublicIpParameters    
    $sourceGatewayIpConfiguration = New-AzureRmVirtualNetworkGatewayIpConfig -Name gwipconfig -SubnetId $sourceGatewaySubnet.Id -PublicIpAddressId $sourcePublicIp.Id
    
    $sourceGatewayParameters = @{
        ResourceGroupName = $sourceResourceGroupName
        Location          = $sourceLocation
        Name              = 's2sgw'
        GatewayType       = 'Vpn'
        VpnType           = 'RouteBased'
        GatewaySku        = 'VpnGw1'
        IpConfigurations  = $sourceGatewayIpConfiguration
    }

    $destinationGatewaySubnet = Get-AzureRmVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $destinationVnet -ErrorAction SilentlyContinue
    $destinationPublicIp = New-AzureRmPublicIpAddress @destinationPublicIpParameters    
    $destinationGatewayIpConfiguration = New-AzureRmVirtualNetworkGatewayIpConfig -Name gwipconfig -SubnetId $destinationGatewaySubnet.Id -PublicIpAddressId $destinationPublicIp.Id
    
    $destinationGatewayParameters = @{
        ResourceGroupName = $destinationResourceGroupName
        Location          = $destinationLocation
        Name              = 's2sgw'
        GatewayType       = 'Vpn'
        VpnType           = 'RouteBased'
        GatewaySku        = 'VpnGw1'
        IpConfigurations  = $destinationGatewayIpConfiguration
    }
        
        
    # Gateway creation
    $sourceGateway = Get-AzureRmVirtualNetworkGateway -Name s2sgw -ResourceGroupName $sourceResourceGroupName -ErrorAction SilentlyContinue
    if (-not $sourceGateway)
    {
        Write-ScreenInfo -TaskStart -Message 'Creating Azure Virtual Network Gateway - this will take some time.'
        $sourceGateway = New-AzureRmVirtualNetworkGateway @sourceGatewayParameters
        Write-ScreenInfo -TaskEnd -Message 'Source gateway created'
    }

    $destinationGateway = Get-AzureRmVirtualNetworkGateway -Name s2sgw -ResourceGroupName $destinationResourceGroupName -ErrorAction SilentlyContinue
    if (-not $destinationGateway)
    {
        Write-ScreenInfo -TaskStart -Message 'Creating Azure Virtual Network Gateway - this will take some time.'
        $destinationGateway = New-AzureRmVirtualNetworkGateway @destinationGatewayParameters
        Write-ScreenInfo -TaskEnd -Message 'Destination gateway created'
    }

    $sourceConnection = @{
        ResourceGroupName      = $sourceResourceGroupName
        Location               = $sourceLocation
        Name                   = 's2sconnection'
        ConnectionType         = 'Vnet2Vnet'
        SharedKey              = 'Somepass1'
        Force                  = $true
        VirtualNetworkGateway1 = $sourceGateway
        VirtualNetworkGateway2 = $destinationGateway
    }

    $destinationConnection = @{
        ResourceGroupName      = $destinationResourceGroupName
        Location               = $destinationLocation
        Name                   = 's2sconnection'
        ConnectionType         = 'Vnet2Vnet'
        SharedKey              = 'Somepass1'
        Force                  = $true
        VirtualNetworkGateway1 = $destinationGateway
        VirtualNetworkGateway2 = $sourceGateway
    }    
        
    [void] (New-AzureRmVirtualNetworkGatewayConnection @sourceConnection)
    [void] (New-AzureRmVirtualNetworkGatewayConnection @destinationConnection)

    Write-Verbose -Message 'Connection created - please allow some time for initial connection.'

    Set-VpnDnsForwarders -SourceLab $SourceLab -DestinationLab $DestinationLab

    Write-LogFunctionExit
}

function Set-VpnDnsForwarders
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $SourceLab,
        [Parameter(Mandatory = $true)]
        [System.String]
        $DestinationLab
    )

    Import-Lab $SourceLab -NoValidation
    $lab = Get-Lab
    $sourceDcs = Get-LabMachine -Role DC, RootDC, FirstChildDC

    Import-Lab $DestinationLab -NoValidation    
    $lab = Get-Lab
    $destinationDcs = Get-LabMachine -Role DC, RootDC, FirstChildDC

    $forestNames = @($sourceDcs) + @($destinationDcs) | Where-Object { $_.Roles.Name -Contains 'RootDC'} | Select-Object -ExpandProperty DomainName
    $forwarders = Get-FullMesh -List $forestNames

    foreach ($forwarder in $forwarders)
    {
        $targetMachine = @($sourceDcs) + @($destinationDcs) | Where-Object { $_.Roles.Name -contains 'RootDC' -and $_.DomainName -eq $forwarder.Source }
        $machineExists = Get-LabMachine | Where-Object {$_.Name -eq $targetMachine.Name -and $_.IpV4Address -eq $targetMachine.IpV4Address}

        if (-not $machineExists)
        {
            if ((Get-Lab).Name -eq $SourceLab)
            {
                Import-Lab -Name $DestinationLab -NoValidation
            }
            else
            {
                Import-Lab -Name $SourceLab -NoValidation
            }
        }

        $masterServers = @($sourceDcs) + @($destinationDcs) | Where-Object { 
            ($_.Roles.Name -contains 'RootDC' -or $_.Roles.Name -contains 'FirstChildDC' -or $_.Roles.Name -contains 'DC') -and $_.DomainName -eq $forwarder.Destination
        }
    
        $cmd = @"
            Write-Verbose "Creating a DNS forwarder on server '$env:COMPUTERNAME'. Forwarder name is '$($forwarder.Destination)' and target DNS server is '$($masterServers.IpV4Address)'..."
            dnscmd localhost /ZoneAdd $($forwarder.Destination) /Forwarder $($masterServers.IpV4Address)
            Write-Verbose '...done'
"@


        Invoke-LabCommand -ComputerName $targetMachine -ScriptBlock ([scriptblock]::Create($cmd)) -NoDisplay
    }
}