Connect-VPN.ps1

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
function Connect-AnyConnect() # {{{
{
  [CmdletBinding(DefaultParameterSetName='Credential')]
  [OutputType([PSCustomObject])]
  Param(
    [Parameter(Position=1, Mandatory=$true)]
    [Alias("Server")]
    [string] $ComputerName,
    [Parameter(Position=2, ParameterSetName='Credential', Mandatory=$true)]
    [System.Management.Automation.PSCredential] $Credential,
    [Parameter(Position=2, ParameterSetName='Plain', Mandatory=$true)]
    [Alias("Username")]
    [string] $User,
    [Parameter(Position=3, ParameterSetName='Plain', Mandatory=$true)]
    [string] $Password
  )
  if ($PSCmdlet.ParameterSetName -eq 'Credential')
  {
    Write-Verbose "Loading PSCredentials"
    $User     = $Credential.UserName
    $Password = $Credential.GetNetworkCredential().password
  }
  else
  {
    $secret     = ConvertTo-SecureString $Password -AsPlainText -Force
    $Credential = New-Object System.Management.Automation.PSCredential($User, $secret)
    $secret     = $null
  }

  # Disconnect as needed
  $temp_session = [PSCustomObject] @{
    Provider='AnyConnect';
    ComputerName=$ComputerName;
    Credential=$Credential;
  }
  if ((Get-AnyConnectStatus -VPNSession $temp_session -Verbose:$false) -ne 'Disconnected')
  {
    Disconnect-AnyConnect -VPNSession $temp_session -Verbose:$Verbose
  }

  # First Stop any VPN cli and ui
  # There must be only one "client" running when connecting
  Get-Process | Where ProcessName -match 'vpn(ui|cli)' | ForEach {
    if (! $_.HasExited)
    {
      Write-Verbose "Stopping process $($_.Name) (pid: $($_.Id))"
      Stop-Process $_.Id
    }
    else
    {
      Write-Verbose "Process $($_.Name) is exiting (pid: $($_.Id))"
    }
  }

  Write-Debug "Starting AnyConnect to $ComputerName as $User (Password: $Password)"
  Write-Verbose "Starting the AnyConnect cli"
  $vpncli = New-Object System.Diagnostics.Process
  $vpncli.StartInfo = New-Object System.Diagnostics.ProcessStartInfo(Get-AnyConnect)
  $vpncli.StartInfo.Arguments = "-s"
  $vpncli.StartInfo.CreateNoWindow  = $true
  $vpncli.StartInfo.UseShellExecute = $false
  $vpncli.StartInfo.RedirectStandardInput  = $true
  $vpncli.StartInfo.RedirectStandardOutput = $true
  #$vpncli.StartInfo.RedirectStandardError = $true

  if (! $vpncli.Start())
  {
    Throw "Cannot start AnyConnect Client, error: $LASTEXITCODE"
  }

  Write-Verbose "Waiting for process to be ready"
  Start-Sleep 2

  Write-Verbose "Sending connect"
  $vpncli.StandardInput.WriteLine('connect ' + $ComputerName)

  Write-Verbose "Sending user"
  $vpncli.StandardInput.WriteLine($User)

  Write-Verbose "Sending password"
  $vpncli.StandardInput.WriteLine($Password)

  Write-Verbose "Reading its output stream"
  $found = $false
  for ($output = $vpncli.StandardOutput.ReadLine(); $output -ne $null; $output = $vpncli.StandardOutput.ReadLine())
  {
    Write-Debug $output
    if ($output -eq ' >> Login failed.')
    {
      Throw [System.Security.Authentication.InvalidCredentialException]
    }
    elseif ($output -match ' >> note: (.*)')
    {
      Write-Warning $matches[1]
    }
    elseif ($output -match ' >> state: (.*)')
    {
      $state = $matches[1]
      Write-Verbose $state
      if ($state -eq 'Connected')
      {
        break
      }
    }
  }
  Start-Process -FilePath (Get-Anyconnect -gui)

  return [PSCustomObject] @{
    Provider='AnyConnect';
    ComputerName=$ComputerName;
    Credential=$Credential;
  }
} #}}}

<#
.SYNOPSIS
  Connects to a VPN Provider.

.DESCRIPTION
  Connects this computer to a given VPN Provider.

.NOTES
  Only Cisco AnyConnect VPNs are supported as of now.

.PARAMETER Provider
  The VPN Provider to use.
  One of: AnyConnect

.PARAMETER ComputerName
  The ComputerName or VPN profile to use.
  The TAB completion will provide the list of possible values depending on the chosen Provider.

.PARAMETER Credential
  The PSCredential to use.

.PARAMETER User
  If no PSCredential is provided, a User and a (plain text) Password must be provided.

.PARAMETER Password
  If no PSCredential is provided, a User and a (plain text) Password must be provided.

.INPUTS
  The ComputerName can be piped in.

.OUTPUTS
  System.Management.Automation.PSObject
  Represents the VPN connection (its Provider, the ComputerName, and the Credential).

.LINK
  https://github.com/gildas/posh-vpn

.EXAMPLE
  $session = Connect-VPN -Provider AnyConnect -ComputerName vpn.acme.com -Credentials (Get-Credential ACME\gildas)

  Description
  -----------
  Connects to a Cisco AnyConnect VPN at vpn.acme.com with the PSCredential entered via Get-Credential

.EXAMPLE
  $session = Connect-VPN -Provider AnyConnect -ComputerName vpn.acme.com -User ACME\gildas -Password s3cr3t

  Description
  -----------
  Connects to a Cisco AnyConnect VPN at vpn.acme.com with the clear text user and password
#>

function Connect-VPN # {{{
{
  [CmdletBinding(DefaultParameterSetName='Credential')]
  [OutputType([PSCustomObject])]
  Param(
    [Parameter(Position=1, Mandatory=$true)]
    [ValidateSet('AnyConnect')]
    [string] $Provider,
    #[Parameter(Position=2, Mandatory=$true)]
    #[Alias("Server")]
    #[string] $ComputerName,
    [Parameter(Position=3, ParameterSetName='Credential', Mandatory=$true)]
    [System.Management.Automation.PSCredential] $Credential,
    [Parameter(Position=3, ParameterSetName='Plain', Mandatory=$true)]
    [Alias("Username")]
    [string] $User,
    [Parameter(Position=4, ParameterSetName='Plain', Mandatory=$true)]
    [string] $Password
  )
  DynamicParam
  {
    $parameters = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary

    #[Parameter(Position=2, Mandatory=$true)]
    $attributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
    $parameter_attribute = New-Object -Type System.Management.Automation.ParameterAttribute
    $parameter_attribute.Position  = 2
    $parameter_attribute.Mandatory = $true
    $parameter_attribute.ValueFromPipeline = $true
    #$parameter_attribute.ParameterSetName = @('Credential', 'Plain')
    $attributes.Add($parameter_attribute)
    if ($Provider -eq 'AnyConnect')
    {
      #[ValidateSet(Get-VPNProfiles -Provider AnyConnect)]
      $validateset = New-Object -Type System.Management.Automation.ValidateSetAttribute(Get-VPNProfile -Provider AnyConnect)
      $attributes.Add($validateset)
    }
    #[Alias("Server")]
    $aliases = New-Object -Type  System.Management.Automation.AliasAttribute(@('Server'))
    $attributes.Add($aliases)
    #[string] $ComputerName,
    $parameter = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ComputerName", [string], $attributes)
    $parameters.Add('ComputerName', $parameter)

    return $parameters
  }
  process
  {
    $PSBoundParameters.Remove('Provider') | Out-Null
    switch($Provider)
    {
      'AnyConnect' { Connect-AnyConnect @PSBoundParameters }
      default      { Throw "Unsupported VPN Provider: $Provider" }
    }
  }
} # }}}