Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
380 commits
Select commit Hold shift + click to select a range
603398b
Add get-ssh-code command information
sykesm Sep 22, 2015
1cc2eb9
Add get-ssh-code to plugin command list
sykesm Sep 22, 2015
9b6d2bf
CLI plugin uses authentication code as ssh password
sykesm Sep 22, 2015
0286037
Remove bearer token authentication with ssh-proxy
sykesm Sep 23, 2015
b5ed976
Update plugin version
sykesm Sep 23, 2015
b88aead
Keep Alive for non-interactive sessions
jfmyers9 Sep 23, 2015
bcca109
Send app instance index when checking ssh_access from CC
jfmyers9 Sep 23, 2015
fc5f549
Add flags to configure BBS HTTP client
luan Sep 24, 2015
f299081
Save off original file infos for comparison
Oct 13, 2015
0b18356
Update README.md
krishicks Oct 19, 2015
efbaf5a
Merge pull request #8 from krishicks/patch-1
emalm Oct 19, 2015
d4f94dc
Clarify scope of CLI version notice
emalm Oct 19, 2015
71b7a68
improve fatal log messages around CF authentication
cwlbraa Nov 11, 2015
3f136c4
dropsondePort is configurable
Nov 19, 2015
9eb2398
Additional logging context in proxy
sykesm Dec 2, 2015
fb7cc19
Wait for exec stream copies to complete
sykesm Dec 2, 2015
33e69be
Simplify SHA1/MD5 fingerprint generators
Dec 2, 2015
9ee2bf9
Merge remote-tracking branch 'origin/pr/14'
jfmyers9 Dec 5, 2015
18955d4
Merge pull request #12 from krishicks/simplify-sha1-md5-generators
SocalNick Dec 7, 2015
6959ab2
Add sftp subsystem to daemon
sykesm Dec 10, 2015
a22901e
Merge remote-tracking branch 'origin/pr/15'
jfmyers9 Dec 14, 2015
166b986
Inherit PATH from sshd environment
jenspinney Dec 16, 2015
bc29b7e
Fix fakeBBS route to v2
jfmyers9 Dec 16, 2015
dcbfba6
Update fakeBBS routes
cwlbraa Dec 18, 2015
0a0f2ba
SSH Proxy emits metrics about the number of connections
andrew-edgar Dec 22, 2015
77140fa
Remove cli plugin from diego-ssh
sykesm Dec 28, 2015
2775bfc
Bump cf-plugin version to 0.2.2
SocalNick Dec 31, 2015
54ad907
Merge remote-tracking branch 'origin/pr/16'
SocalNick Dec 31, 2015
550820a
Revert "Inherit PATH from sshd environment"
cwlbraa Jan 12, 2016
138c885
Add logging when metric sending fails
ameowlia Jan 12, 2016
6377d20
Take in UAA basic auth Password and Username as separate flags
jfmyers9 Jan 22, 2016
c542856
Update username and password in fake UUA
andrew-edgar Jan 25, 2016
dbe8750
Remove u.User for new parameterized values
jenspinney Jan 25, 2016
214bf27
Update ssh-proxy to use locket service registration
jenspinney Jan 21, 2016
f66b4a5
Rename consulClient constructor methods
jfmyers9 Jan 30, 2016
2be354e
Rewrite listen address using CF_INSTANCE_PORTS on Windows
mhoran Feb 12, 2016
c2e0008
add flags for specifying allowed cipher,mac,kex algorithms
JamesClonk Feb 17, 2016
5e0bd9d
Drain connections on server shutdown
jfmyers9 Feb 18, 2016
7be5d91
Use updated sftp Server constructor
sykesm Feb 22, 2016
0ae78e7
Restrict regexes validating diego and cf auth usernames
jenspinney Feb 23, 2016
a4977de
Merge pull request #18 from swisscom/master
ameowlia Feb 23, 2016
6c373b2
Merge branch 'update-sftp' of https://github.com/sykesm/diego-ssh int…
Feb 26, 2016
5bd77ce
Merge branch 'sykesm-update-sftp'
Feb 26, 2016
0bcbdc5
Revert "Revert "Inherit PATH from sshd environment""
andrew-edgar Feb 25, 2016
cca2f2a
add flags to ssh-proxy for specifying allowed cipher,mac,kex algorithms
JamesClonk Mar 7, 2016
e0c3eb9
Update LICENSE and NOTICE
emalm Mar 8, 2016
9eac0dc
Fix flaky test
jenspinney Mar 10, 2016
8292045
Revert "Revert "Revert "Inherit PATH from sshd environment"""
luan Mar 10, 2016
bf0955b
Merge remote-tracking branch 'origin/pr/21'
luan Mar 10, 2016
8e783ca
CloseWrite when copy and closing for directtcip
jfmyers9 Mar 21, 2016
d7edb85
Wait for command to start before closing stdin
andrew-edgar Mar 23, 2016
1047a12
Update LICENSE and NOTICE
emalm Mar 25, 2016
c3de54e
Wait for command to start before signalling
jfmyers9 Mar 25, 2016
9b47eab
Wait on closing target/source channel after proxying requests
jfmyers9 Mar 28, 2016
f9b7545
Remove test debugging log line
Mar 29, 2016
1a29996
Update NOTICE
emalm Mar 31, 2016
8c6a69b
Copy stderr as well as stdout
cwlbraa Apr 8, 2016
5675caa
handle stderr copying in parallel
cwlbraa Apr 12, 2016
61bf75c
bbs.Client -> bbs.InternalClient
jfmyers9 Apr 19, 2016
46738e8
Rename fake_bbs.FakeClient->fake_bbs.FakeInternalClient
jenspinney Apr 28, 2016
44328c2
Add logger to bbs client methods
jfmyers9 May 5, 2016
410cb55
Remove unused variables from tests
jenspinney Jun 9, 2016
183c5ab
Update repository links
joachimvaldez Jun 23, 2016
1aa15c1
Update import location of bbs
jfmyers9 Jun 27, 2016
ff4e16e
Update consuladapter import location
jfmyers9 Jun 28, 2016
1aa0d9f
Update locket import location
jfmyers9 Jun 28, 2016
4976a8d
Update and rename cf-debug-server -> debugserver
jfmyers9 Jun 28, 2016
816d867
Update and rename cf-lager -> cflager
nimakaviani Jun 28, 2016
3acbdfe
Update and rename cf_http -> cfhttp
nimakaviani Jun 28, 2016
aded50a
Update import location for diego-ssh
nimakaviani Jun 28, 2016
d08a40f
Add notice to import from `code.cloudfoundry.org`
jfmyers9 Jun 28, 2016
c900aa8
Move clock to code.clock.org
jfmyers9 Jun 30, 2016
c3af3a0
Improve AuthLogCallback logging
jfmyers9 Jun 30, 2016
3e7d2f4
Update example passwords
Jun 30, 2016
09a8c83
Move lager to code.cloudfoundry.org
luan Jun 30, 2016
c6292bb
Use env vars instead of params.
andrew-edgar Jul 7, 2016
0c1efef
Unset env vars in afterEach of tests
andrew-edgar Jul 7, 2016
3baa210
re-exec the ssh daemon using environment variables instead of cli args
luan Jul 15, 2016
b5713cc
fix the tests broken from previous commit
joachimvaldez Jul 18, 2016
46bd01f
Merge branch 'spike-exec'
jvshahid Jul 18, 2016
c8feb81
Rename 'appplication' to 'application'
wendorf Jul 18, 2016
72c4d7e
set the PATH env variable properly
Jul 18, 2016
6b726c1
propagate logLevel and debugAddr to diego-sshd process
joachimvaldez Jul 19, 2016
f3f25a7
Merge pull request #22 from wendorf/master
jenspinney Jul 19, 2016
32bf6d5
update test with new r2 route
caod123 Jul 21, 2016
3ce14ee
Add log message when proxy session ends
joachimvaldez Aug 18, 2016
ea7a826
Add healthcheck server to ssh proxy
caod123 Oct 6, 2016
978f6c6
Add HealthCheckAddress arg to test to configure port between parallel
caod123 Oct 13, 2016
1d5d857
Use rata multiplexer and create new package for healthcheck handler
jvshahid Oct 17, 2016
c655138
Fix go lint errors to make go rename possible
jenspinney Oct 21, 2016
a3238a0
cco/cflager -> cco/lager/lagerflags
jvshahid Oct 21, 2016
9ddfd3b
Add a KeepAlive to ssh-proxy httpclient
caod123 Oct 21, 2016
7847384
Add logging of username and principal for audit
Nov 16, 2016
86da3cf
ssh-proxy config is passed in through a json file
jfmyers9 Nov 17, 2016
c31932f
use json configuration for lager and debugserver
jfmyers9 Nov 21, 2016
a3d710c
cleanup temp directories in AfterEach
jfmyers9 Nov 22, 2016
30305a9
Don't try to syscall.exec on Windows
Dec 12, 2016
fcd0983
Merge pull request #28 from mhoran/no-exec-windows
caod123 Dec 15, 2016
574f125
pass ClusterRunnerConfig to NewClusterRunner
nimakaviani Jan 6, 2017
18cdb35
Bump consul TTL timeout to 20s
Dec 7, 2016
69d0750
use durationjson for time.Duration json logic
jfmyers9 Jan 17, 2017
8f216fb
Enforce canonical import path
caod123 Feb 6, 2017
a327615
adds uaa_ca_cert to ssh-proxy config
crhino Feb 13, 2017
5bc46ed
add before each to reset uaaCACert
jfmyers9 Feb 15, 2017
7497fcf
Update LICENSE and NOTICE
emalm Feb 23, 2017
931ad9a
Ignore unknown opcodes/terminal modes
jvshahid Mar 30, 2017
1a750f2
add required HostKeyCallback to ssh.ClientConfig
jfmyers9 Apr 13, 2017
3dff1c7
Revert "add required HostKeyCallback to ssh.ClientConfig"
jfmyers9 Apr 14, 2017
72df32a
Close config file after reading.
jvshahid Apr 18, 2017
f7fdb2a
updated the tests to include instance ip address in the ActualLRPNetInfo
May 9, 2017
1475d13
add some debug logging to the ssh daemon
crhino Jul 6, 2017
19d2baa
updated the tests to include instance ip address in the ActualLRPNetInfo
May 9, 2017
e1e411d
Merge branch 'keep-this-branch'
Jul 12, 2017
d0a23d3
[ #148020689 ] sets the GOMAXPROCS to 1
jvshahid Jul 11, 2017
5c819b8
fix flakey tests
crhino Jul 17, 2017
90247b6
allow the ssh proxy to connect directory to the container ip and port
jvshahid Aug 4, 2017
8982225
Update proxy to explicitly set HostKeyCallback when no HostFingerprint
Aug 9, 2017
a0438f7
Update tests to explicitly set HostKeyCallback
swetharepakula Aug 9, 2017
84db2a1
Use a build flag to opt-in to external port mapping
sesmith177 Aug 15, 2017
512a1c1
Make unit tests pass on Windows.
Aug 22, 2017
dabbdc9
remove chmod from unit tests
crhino Aug 22, 2017
468b07b
Add windows support using WinPTY
sesmith177 Sep 14, 2017
f68f8a4
add flag for enabling consul service registration
Sep 14, 2017
c73d30c
Merge branch 'greenhouse-org-w2016'
nimakaviani Oct 3, 2017
602a5a6
enforce canonical import path
nimakaviani Oct 3, 2017
df8cd01
fix a few random things
jvshahid Oct 5, 2017
e055be4
use loggregator v2 to emit metrics and app logs
swetharepakula Oct 6, 2017
fe896d7
normalize the executed path to avoid flakes in units-windows
jvshahid Oct 13, 2017
9f06b1d
account for both Path (on windows) and PATH on Linux
jvshahid Oct 13, 2017
e1c7132
Add a idle timeout to incoming connections to the ssh-proxy and ssh-d…
jvshahid Oct 27, 2017
7cbc341
regenerate all fakes
nimakaviani Oct 27, 2017
fab2259
fix the flake with expected timeout sent to the client
jvshahid Oct 27, 2017
fded206
identify diego-ssh server to clients
johnsonj Nov 8, 2017
dc29936
Name the sshd / ssh-proxy servers.
nimakaviani Nov 20, 2017
878a23c
Rename metrics constants to follow convention
Nov 30, 2017
4f2112b
Use portauthority to allocate ports in tests.
Dec 6, 2017
61a4d27
fix some tests that were broken since SendMetric signature has changed
jvshahid Dec 8, 2017
9a61d39
Fix port range for portAllocator
goonzoid Feb 2, 2018
65db946
bbs communicate is now required to be secure
sjolicoeur Feb 15, 2018
b0cbc38
get rid of etcd references
jvshahid Feb 16, 2018
1000dd7
Remove loggregator v1 / dropsonde support
goonzoid Feb 24, 2018
2deb396
Remove unused fakeLogSender
jvshahid Feb 26, 2018
de8b027
Fix potential race in Server
charlievieth Feb 28, 2018
30df0e6
Changed the insecure defaults for the ssh-proxy and sshd
flawedmatrix Mar 22, 2018
e65bd26
Added hmac-sha2-256 for backwards compatibility
sjolicoeur Mar 23, 2018
c9dc416
add support for remote->local port forwarding
Apr 13, 2018
22aea32
some cleanup
jvshahid Apr 19, 2018
c1520bf
fix a few assertions to work on windows
jvshahid Apr 23, 2018
58eb902
add ssh ciphers aes256-ctr, aes192-ctr, aes128-ctr
nimakaviani Apr 24, 2018
74208bc
remove unused variable
jvshahid May 18, 2018
2923b71
use portauthority to allocate consul's ports
jvshahid May 18, 2018
99e7818
fix a flaky test
jvshahid May 18, 2018
b58d49a
minor changes to the test to avoid binding to a used port and flakiness
jvshahid May 21, 2018
9b3f460
Update to use new AcutalLRPGroup.Resolve function
sjolicoeur May 17, 2018
1174556
Upgrade jwt-go library.
andyliuliming Apr 4, 2018
1f4a252
remove a binary that was checked in accidentally
jvshahid Jun 18, 2018
b514749
use Eventually instead of Expect to make the test less flaky
jvshahid Jun 19, 2018
7eef40b
assert the SSH Proxy won't start if it cannot connect to the loggreto…
jvshahid Jun 29, 2018
091bfa6
Revert "assert the SSH Proxy won't start if it cannot connect to the …
Jul 11, 2018
fa05406
Revert "Revert "assert the SSH Proxy won't start if it cannot connect…
sunjayBhatia Jul 13, 2018
bbfc30d
Remove default config from diego-ssh
jvshahid Sep 12, 2018
2b75a7a
Ensure signal is actually sent to long running process
sunjayBhatia Oct 15, 2018
0ea1343
Fix the mock BBS server to use the new http paths
jvshahid Oct 15, 2018
71c5630
Support connecting to the daemon over TLS
Nov 1, 2018
402201c
Error if the backend tls certificate isn't specified and backend tls …
jvshahid Nov 1, 2018
0f5b562
Avoid logging private key in proxy dialer
emalm Nov 3, 2018
0d8d8a4
Fix two edge cases when TLS is turned on
jvshahid Nov 21, 2018
744d42f
ssh-proxy can be configured with a CC CA cert
sunjayBhatia Jan 10, 2019
c3bf02c
eliminate unused code
Jan 18, 2019
421727c
replaced cfhttp with tlsconfig
flawedmatrix Feb 16, 2019
9806bf5
Switches ssh-proxy to use new initializer for BBS client
flawedmatrix Feb 22, 2019
f259678
Revert "Switches ssh-proxy to use new initializer for BBS client"
Feb 27, 2019
ff188ef
Add disable_health_check_server config option
Feb 27, 2019
9928ba0
Revert "Revert "Switches ssh-proxy to use new initializer for BBS cli…
flawedmatrix Feb 27, 2019
8cc14e0
Update expired certs
Mar 5, 2019
fd9db4f
cflinuxfs{2,3}
Apr 19, 2019
0f92f36
Advertise conn pref: Diego cell IP vs Instance IP
May 23, 2019
7053984
Merge branch 'jrussett-pas+win+nsx-t'
flawedmatrix May 28, 2019
93ba2e0
Use enum for NetInfo preferred address to reduce downtime of ssh
sunjayBhatia Jun 6, 2019
b23c508
Use tags signature for emitting metric
Jun 20, 2019
4e330a2
Use flattened ActualLRPs BBS endpoint
Jul 26, 2019
d560480
Delete expired and unnecessary certs
Aug 21, 2019
051ad77
Regenerate fakes to avoid data race
mariash Nov 27, 2019
5e233c1
Update README with URL to diego-release issues
mariash Jan 21, 2020
6f19a31
Update PR template
mariash Jan 25, 2020
01335ca
update to latest sftp server
robertjsullivan Mar 12, 2020
517d22c
bump to latest sftp server for windows channel handler
robertjsullivan Mar 12, 2020
89075dd
Generate certs on the fly in all tests.
mdelillo Sep 21, 2020
3baf789
Fix the unit tests on windows.
Sep 25, 2020
f0a2d8d
as of Go1.16 CertPools can't be compared
May 12, 2021
5473ddd
Convert pathing for go mod'ed tests
jrussett May 19, 2021
8beefc1
Use the correct import path
Jun 15, 2021
810ba66
Switch to golang-jwt/jwt instead of dgrijalva/jwt
mariash Oct 19, 2021
991c3a9
Replace GinkgoParallelNode with GinkgoParallelProcess
mariash Jul 19, 2022
71ed07f
Add tests to account for new AEAD behavior from x/crypto
reneighbor Sep 6, 2022
0fc4f3a
Remove consul from diego-ssh
reneighbor Sep 29, 2022
1003fb5
Bump to ginkgo/v2 and lager/v3 (#47)
winkingturtle-vmw Apr 6, 2023
62afa25
go fmt
Apr 11, 2023
1bdd96c
Update bbs client calls with trace ID (#48)
mariash May 23, 2023
7461829
Add CODEOWNERS file in preparation for branch protection rules (#49)
geofffranks Jun 12, 2023
af9d79f
Switch to preferred ciphers for more up to date x/crypto/ssh (#50)
Aug 10, 2023
08b408d
Fix issue with go vet warnings for unsafe.Pointer
Oct 18, 2023
0db8c36
With oss ci export (#51)
winkingturtle-vmw Nov 14, 2023
182f15a
update error message with [email protected] algorithm
ameowlia Dec 18, 2023
d9a2944
update error message with [email protected] algorithm
ameowlia Dec 18, 2023
129a002
Prefer time.Until(timeObj) for staticcheck
geofffranks Feb 27, 2024
8b59f7d
Use fmt.Errorf() instead of errors.New() + fmt.Sprintf()
geofffranks Feb 27, 2024
f2368be
remove unneded selects
geofffranks Feb 27, 2024
4f068d9
Remove unnecessary sprintf
geofffranks Feb 27, 2024
19bc255
Use print when not needing printf formatting
geofffranks Feb 28, 2024
d38c194
Check errors before overwriting them with new errors
geofffranks Feb 28, 2024
e5eaed3
Remove unexecuted code branch
geofffranks Feb 28, 2024
3db90b9
remove unnecessary sprintf() call
geofffranks Feb 28, 2024
d0e61fe
Check err obj
geofffranks Feb 28, 2024
ac210b7
Stop using deprecated ioutil package
geofffranks Feb 29, 2024
dd16875
ignore deprecation warning for tlsconfig.RootCAs.Subjects() since we …
geofffranks Mar 1, 2024
16a2bc4
replace deprecated docker term with moby term
geofffranks Mar 1, 2024
a73aaa4
Stop using net.error.Temporary() where we can, and ignore the staticc…
geofffranks Mar 11, 2024
adc1f26
Don't check errors on jwt parsing, we use it only for parsing info, n…
geofffranks Mar 8, 2024
df0301f
Serialize the ssh-proxy tests that re-use the same port
geofffranks Mar 11, 2024
290dd69
Don't check error after all
geofffranks Mar 21, 2024
f465a65
Sync .github dir templates
tas-runtime-bot Apr 8, 2024
51df591
Update go-loggregator to v9 (#55)
Birdrock May 21, 2024
ddb0135
Avoid port collision when allocating multiple ports (#56)
mariash Jul 17, 2024
0e1b7b1
Wait for the server to stop in AfterEach (#57)
mariash Aug 8, 2024
7b0458d
Catch or explicitly ignore unhandled errors
geofffranks Sep 23, 2024
b4cd6f2
move info from readme into individual ordered docs
ameowlia Oct 1, 2024
3efd7e8
Sync README.md
tas-runtime-bot Oct 1, 2024
016d223
Use SHA256 Instead of SHA1
MarcPaquette Sep 4, 2024
fcfa02a
WIP Update name for SHA256
MarcPaquette Oct 8, 2024
e96542e
Support SHA1 & SHA256
MarcPaquette Oct 10, 2024
ec3d721
Sync README.md
tas-runtime-bot Oct 25, 2024
fab8c5a
Sync README.md
tas-runtime-bot Oct 26, 2024
b5002bc
Sync README.md
tas-runtime-bot Oct 29, 2024
4d6c6f7
Sync README.md
tas-runtime-bot Dec 10, 2024
badd9d4
Remove chacha20 cipher from cmd/ssh-proxy/main.go
DimitarSch Jan 7, 2025
04a92b0
Remove chacha20 cipher from cmd/sshd/main.go
DimitarSch Jan 7, 2025
680f78e
Update ssh-proxy/main_test.go
DimitarSch Jan 9, 2025
7049bbe
Update sshd/main_test.go
DimitarSch Jan 9, 2025
a6d7524
Use the correct package for SHA256
winkingturtle-vmw Apr 24, 2025
739cdc5
fix typo
winkingturtle-vmw Apr 24, 2025
1853596
Update wording for error match
mariash Aug 5, 2025
4b24269
More error wording change
mariash Aug 5, 2025
5542e25
Fix other error matching testst
mariash Aug 6, 2025
3a36901
Fix sshd tests with error wording
mariash Aug 6, 2025
bd398c2
Fix error message
mariash Aug 7, 2025
b824aeb
remove diego-ssh submodule entry
kart2bc Aug 26, 2025
b28f013
Add 'src/code.cloudfoundry.org/diego-ssh/' from commit 'bd398c2f4b891…
kart2bc Aug 26, 2025
5ad37d6
Inline submodule diego-ssh into main repo
kart2bc Aug 26, 2025
0138f4e
Merge branch 'develop' into diego-ssh-inline-mod
ameowlia Sep 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,6 @@
path = src/code.cloudfoundry.org/buildpackapplifecycle
url = https://github.com/cloudfoundry/buildpackapplifecycle
branch = main
[submodule "src/code.cloudfoundry.org/diego-ssh"]
path = src/code.cloudfoundry.org/diego-ssh
url = https://github.com/cloudfoundry/diego-ssh
branch = main
[submodule "src/code.cloudfoundry.org/route-emitter"]
path = src/code.cloudfoundry.org/route-emitter
url = https://github.com/cloudfoundry/route-emitter
Expand Down
1 change: 0 additions & 1 deletion src/code.cloudfoundry.org/diego-ssh
Submodule diego-ssh deleted from bd398c
8 changes: 8 additions & 0 deletions src/code.cloudfoundry.org/diego-ssh/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.coverprofile
*.exe
*.swp
*.test
*~
.DS_Store
.idea
tags
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package authenticators_test

import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"

"testing"
)

func TestAuthenticators(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Authenticators Suite")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
package authenticators

import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"

"code.cloudfoundry.org/lager/v3"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/ssh"
)

type CFAuthenticator struct {
logger lager.Logger
httpClient *http.Client
ccURL string
uaaTokenURL string
uaaPassword string
uaaUsername string
permissionsBuilder PermissionsBuilder
}

type AppSSHResponse struct {
ProcessGuid string `json:"process_guid"`
}

type UAAAuthTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
}

var CFUserRegex *regexp.Regexp = regexp.MustCompile(`cf:([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/(\d+)`)

func NewCFAuthenticator(
logger lager.Logger,
httpClient *http.Client,
ccURL string,
uaaTokenURL string,
uaaUsername string,
uaaPassword string,
permissionsBuilder PermissionsBuilder,
) *CFAuthenticator {
return &CFAuthenticator{
logger: logger,
httpClient: httpClient,
ccURL: ccURL,
uaaTokenURL: uaaTokenURL,
uaaUsername: uaaUsername,
uaaPassword: uaaPassword,
permissionsBuilder: permissionsBuilder,
}
}

func (cfa *CFAuthenticator) UserRegexp() *regexp.Regexp {
return CFUserRegex
}

func (cfa *CFAuthenticator) Authenticate(metadata ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
logger := cfa.logger.Session("cf-authenticate")
logger.Info("authenticate-starting")
defer logger.Info("authenticate-finished")

if !CFUserRegex.MatchString(metadata.User()) {
logger.Error("regex-match-fail", InvalidCredentialsErr)
return nil, InvalidCredentialsErr
}

guidAndIndex := CFUserRegex.FindStringSubmatch(metadata.User())

appGuid := guidAndIndex[1]

index, err := strconv.Atoi(guidAndIndex[2])
if err != nil {
logger.Error("atoi-failed", err)
return nil, InvalidCredentialsErr
}

cred, err := cfa.exchangeAccessCodeForToken(logger, string(password))
if err != nil {
return nil, err
}

parts := strings.Split(cred, " ")
if len(parts) != 2 {
return nil, AuthenticationFailedErr
}
tokenString := parts[1]
// When parsing the certificate validating the signature is not required and we don't readily have the
// certificate to validate the signature. This is just to parse the second information part of the token anyway.
token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("Doesntmatter"), nil
})

username, ok := token.Claims.(jwt.MapClaims)["user_name"].(string)
if !ok {
username = "unknown"
}
principal, ok := token.Claims.(jwt.MapClaims)["user_id"].(string)
if !ok {
principal = "unknown"
}

logger = logger.WithData(lager.Data{
"app": fmt.Sprintf("%s/%d", appGuid, index),
"principal": principal,
"username": username,
})

processGuid, err := cfa.checkAccess(logger, appGuid, index, string(cred))
if err != nil {
return nil, err
}

permissions, err := cfa.permissionsBuilder.Build(logger, processGuid, index, metadata)
if err != nil {
logger.Error("building-ssh-permissions-failed", err)
}

logger.Info("app-access-success")

return permissions, err
}

func (cfa *CFAuthenticator) exchangeAccessCodeForToken(logger lager.Logger, code string) (string, error) {
logger = logger.Session("exchange-access-code-for-token")

formValues := make(url.Values)
formValues.Set("grant_type", "authorization_code")
formValues.Set("code", code)

req, err := http.NewRequest("POST", cfa.uaaTokenURL, strings.NewReader(formValues.Encode()))
if err != nil {
return "", err
}

req.SetBasicAuth(cfa.uaaUsername, cfa.uaaPassword)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := cfa.httpClient.Do(req)
if err != nil {
logger.Error("request-failed", err)
return "", AuthenticationFailedErr
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
logger.Error("response-status-not-ok", AuthenticationFailedErr, lager.Data{
"status-code": resp.StatusCode,
})
return "", AuthenticationFailedErr
}

var tokenResponse UAAAuthTokenResponse
err = json.NewDecoder(resp.Body).Decode(&tokenResponse)
if err != nil {
logger.Error("decode-token-response-failed", err)
return "", AuthenticationFailedErr
}

return fmt.Sprintf("%s %s", tokenResponse.TokenType, tokenResponse.AccessToken), nil
}

func (cfa *CFAuthenticator) checkAccess(logger lager.Logger, appGuid string, index int, token string) (string, error) {
path := fmt.Sprintf("%s/internal/apps/%s/ssh_access/%d", cfa.ccURL, appGuid, index)

req, err := http.NewRequest("GET", path, nil)
if err != nil {
logger.Error("creating-request-failed", InvalidRequestErr)
return "", InvalidRequestErr
}
req.Header.Add("Authorization", token)

resp, err := cfa.httpClient.Do(req)
if err != nil {
logger.Error("fetching-app-failed", err)
return "", err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
logger.Error("fetching-app-failed", FetchAppFailedErr, lager.Data{
"StatusCode": resp.Status,
"ResponseBody": resp.Body,
})
return "", FetchAppFailedErr
}

var app AppSSHResponse
err = json.NewDecoder(resp.Body).Decode(&app)
if err != nil {
logger.Error("invalid-cc-response", err)
return "", InvalidCCResponse
}

return app.ProcessGuid, nil
}
Loading