Commit 2b5e6fda authored by Michael Völske's avatar Michael Völske

add k8s tool and first two commands

parent 40548975
......@@ -14,7 +14,8 @@
"elasticsearch": "Helper scripts for managing Elasticsearch on the Betaweb cluster.",
"git": "Helper scripts for working with the Webis Git server and GitLab instance.",
"webis20": "Storage Management Scripts, need direct access to RAID Controller and MegaCLI installed",
"pki": "Webis TLS PKI Tools"
"pki": "Webis TLS PKI Tools",
"k8s": "Kubernetes tools"
},
"commands_aliases": {
......
#!/bin/bash
# Connect kubectl to the testing cluster
#
# Copyright 2018-today
#
# Project WEBIS
# Author: Michael Völske
scriptPath=${0%/*}
. "$scriptPath"/../../libs/bashhelper.sh
. "$scriptPath"/../../libs/shflags
check_tools "kubectl"
usage() {
echo "
usage:
$(basename "$0") <your-user-name>
"
exit 1
}
FLAGS_HELP=$(usage)
export FLAGS_HELP
FLAGS "$@" || exit 1 # Parse command line arguments.
eval set -- "${FLAGS_ARGV}" || true
main() {
if [ "$#" -eq 0 ]; then
logError "Missing arguments see:"
usage
fi
kubectl config set-cluster webis6 --server=https://webis6:6443 --insecure-skip-tls-verify=true
kubectl config set-context webis6 --cluster=webis6 --user="$1"
kubectl config use-context webis6
}
main "$@"
#!/bin/bash
# Set up OpenID authentication for kubernetes access
#
# Copyright 2018-today
#
# Project WEBIS
# Author: Michael Völske
########################################################################
## This is bash:
"true" '''\'
set -e
scriptPath=${0%/*}
. "$scriptPath"/../../libs/bashhelper.sh
check_tools "python3" "kubectl"
mkdir -vp ~/.webiscmd
VENV=$(mktemp -p ~/.webiscmd -d)
python3 -m venv "${VENV}"
. "${VENV}/bin/activate"
echo -n Setting up...
pip -q install oic
echo Done.
HERE=$(readlink -f "$0" )
export OIC_TEMP_DIR="${VENV}"
python3 ${HERE} $@
rm -rf "${VENV}"
exit 0
'''
########################################################################
## This is Python:
OPENID_APP_ID = "webis-k8s-auth"
OPENID_APP_SECRET = "not-so-secret"
OPENID_ISSUER = 'https://dex.webis.de'
CALLBACK_URL = 'https://localhost:42001/oidcb'
from oic import rndstr
from oic.oic import Client
from oic.oic.message import RegistrationResponse, Claims, ClaimsRequest, AuthorizationResponse
from oic.utils.authn.client import CLIENT_AUTHN_METHOD
from oic.utils.http_util import Redirect
from http.server import HTTPServer, BaseHTTPRequestHandler
from threading import Thread
import os
import os
import ssl
import sys
import time
import traceback
import urllib.parse as urlparse
client = Client(client_authn_method=CLIENT_AUTHN_METHOD)
provider_info = client.provider_config(OPENID_ISSUER)
info = {"client_id": OPENID_APP_ID, "client_secret": OPENID_APP_SECRET, "redirect_uris": [CALLBACK_URL]}
client_reg = RegistrationResponse(**info)
client.store_registration_info(client_reg)
session = {}
session["state"] = rndstr()
session["nonce"] = rndstr()
args = {
"client_id": client.client_id,
"response_type": ['code'],
#"scope": "openid", # <- for gitlab
"scope": ['openid', 'offline_access', 'email', 'groups', 'profile'],
"nonce": session["nonce"],
"redirect_uri": client.registration_response["redirect_uris"][0],
"state": session["state"],
"claims": ClaimsRequest(
id_token=Claims(name={'essential': True}, groups={'essential': True}),
userinfo=Claims(name={'essential': True}, groups={'essential': True})
)
}
auth_req = client.construct_AuthorizationRequest(request_args=args)
login_url = auth_req.request(client.authorization_endpoint)
CERT=os.path.join(os.environ['OIC_TEMP_DIR'], 'cert.pem')
KEY=os.path.join(os.environ['OIC_TEMP_DIR'], 'key.pem')
os.system('openssl req -subj "/CN=localhost" -new -x509 -days 1095 -nodes -newkey rsa:2048 -out %s -keyout %s' % (CERT, KEY))
server = None
def stop_server():
global server
server.shutdown()
server.server_close()
t1 = Thread(target=stop_server)
aresp = None
class H(BaseHTTPRequestHandler):
def do_GET(self, **kwargs):
global aresp
try:
response = self.path.split('?')[-1]
aresp = client.parse_response(AuthorizationResponse, response, sformat='urlencoded')
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
res = 'Ok. Received Token: {}'.format(dict(aresp))
res += '\n You\'re done here. Continue in the terminal.'
self.wfile.write(res.encode('utf8'))
except Exception as ex:
self.send_response(500)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b'ERROR -- check terminal')
traceback.print_exc()
t1.start()
server = HTTPServer(('localhost', 42001), H)
ctx = ssl.SSLContext()
ctx.load_cert_chain(certfile=CERT, keyfile=KEY)
server.socket = ctx.wrap_socket (server.socket, server_side=True)
def click_link():
time.sleep(0.5)
os.system("xdg-open '%s'" % login_url)
print(
'*'*72,
'This is your OpenId Login URL:',
'%s' % login_url,
'*'*72,
'0. Read these instructions, then press Return.',
'1. If no browser tab/window opens, visit the above URL manually.',
'2. In the browser, you will be asked to sign into Gitlab if necessary (existing sessions will be re-used). Follow instructions from Gitlab, if any (e.g. for 2FA).',
'3. Once you are signed in, accept the SSL certificate prompt for %s, then return to this terminal.' % CALLBACK_URL,
sep='\n')
sys.stdin.readline()
t2 = Thread(target=click_link)
t2.start()
server.serve_forever()
t1.join()
t2.join()
os.system('rm -f ./cert.pem ./key.pem')
assert aresp["state"] == session["state"]
args = {
"code": aresp["code"]
}
resp = client.do_access_token_request(state=aresp["state"],
request_args=args,
authn_method="client_secret_basic")
itok = resp['id_token']
kctl_cmd = "kubectl config set-credentials {u} \
--auth-provider=oidc \
--auth-provider-arg=idp-issuer-url={url} \
--auth-provider-arg=client-id={cid} \
--auth-provider-arg=client-secret={cs} \
--auth-provider-arg=refresh-token={rtok} \
".format(
u=itok['email'], url=itok['iss'], cid=OPENID_APP_ID,
cs=OPENID_APP_SECRET, rtok=resp['refresh_token'])
os.system(kctl_cmd)
print('You should now have kubectl configured for OpenID authentication. Try running `kubectl get all` after setting up a cluster connection, and adding yourself to the proper gitlab groups.')
print('Your Kubernetes username is:', itok['email'])
# Local Variables:
# mode: python
# End:
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment