markusthoemmes closed pull request #2517: Support client certificate verify on
server side
URL: https://github.com/apache/incubator-openwhisk/pull/2517
This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:
As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):
diff --git a/ansible/group_vars/all b/ansible/group_vars/all
index 13a2a657a6..cc395ffcbd 100644
--- a/ansible/group_vars/all
+++ b/ansible/group_vars/all
@@ -157,7 +157,7 @@ nginx:
password_enabled: false
password_file: "ssl.pass"
client_ca_cert: "{{ openwhisk_client_ca_cert |
default('openwhisk-client-ca-cert.pem') }}"
- verify_client: "{{ nginx_ssl_verify_client | default('off') }}"
+ verify_client: "{{ nginx_ssl_verify_client | default('optional') }}"
# These are the variables to define all database relevant settings.
# The authKeys are the users, that are initially created to use OpenWhisk.
@@ -221,6 +221,10 @@ catalog_namespace: "/whisk.system"
# By default, we take the key from {{ openwhisk_home
}}/ansible/files/auth.whisk.system.
catalog_auth_key: "{{ openwhisk_home }}/ansible/files/auth.whisk.system"
+# The catalog_cert_file and catalog_key_file is used to authenticate the
openwhisk service when nginx ssl configuration is opened.
+catalog_cert_file: "{{ openwhisk_home
}}/ansible/roles/nginx/files/openwhisk-client-cert-whisk-system.pem"
+catalog_key_file: "{{ openwhisk_home
}}/ansible/roles/nginx/files/openwhisk-client-key-whisk-system.pem"
+
# The catalog_repos is used to specify all the catalog names and repository
URLs,
# so that openwhisk knows where to download the catalog and install them. The
key
# specifies the catalog name and the url saves the URL of the repository. The
location
@@ -243,11 +247,11 @@ catalog_auth_key: "{{ openwhisk_home
}}/ansible/files/auth.whisk.system"
#
catalog_repos:
openwhisk-catalog:
- url: https://github.com/apache/incubator-openwhisk-catalog.git
+ url: https://github.com/ningyougang/incubator-openwhisk-catalog.git
# Set the local location as the same level as openwhisk home, but it can
be changed.
location: "{{ openwhisk_home }}/../openwhisk-catalog"
- version: "HEAD"
- repo_update: "no"
+ version: "suppport-client-certificate"
+ repo_update: "yes"
openwhisk_cli_tag: "{{ lookup('ini', 'git_tag section=openwhisk-cli file={{
openwhisk_home }}/ansible/files/package-versions.ini') }}"
diff --git a/ansible/roles/controller/tasks/deploy.yml
b/ansible/roles/controller/tasks/deploy.yml
index 71b62870cf..469663244c 100644
--- a/ansible/roles/controller/tasks/deploy.yml
+++ b/ansible/roles/controller/tasks/deploy.yml
@@ -57,6 +57,7 @@
"LOADBALANCER_INVOKERBUSYTHRESHOLD": "{{ invoker.busyThreshold }}"
"RUNTIMES_MANIFEST": "{{ runtimesManifest | to_json }}"
+ "WHISK_SSL_CLIENT_VERIFICATION": "{{ nginx.ssl.verify_client }}"
volumes:
- "{{ whisk_logs_dir }}/controller{{
groups['controllers'].index(inventory_hostname) }}:/logs"
ports:
diff --git a/ansible/roles/nginx/files/genssl.sh
b/ansible/roles/nginx/files/genssl.sh
index d78400ddfe..d79cdbcc93 100755
--- a/ansible/roles/nginx/files/genssl.sh
+++ b/ansible/roles/nginx/files/genssl.sh
@@ -49,30 +49,56 @@ else
-out "$SCRIPTDIR/openwhisk-client-ca-cert.pem" \
-days 365 -sha1 -extensions v3_ca
- echo generating client key
- openssl genrsa -aes256 -passout pass:$PASSWORD -out
"$SCRIPTDIR/openwhisk-client-key.pem" 2048
+ echo generating subject:whisk.system\'s client key
+ openssl genrsa -aes256 -passout pass:$PASSWORD -out
"$SCRIPTDIR/openwhisk-client-key-whisk-system.pem" 2048
- echo generating client certificate csr file
+ echo generating subject:whisk.system\'s client certificate csr file
openssl req -new \
- -key "$SCRIPTDIR/openwhisk-client-key.pem" \
+ -key "$SCRIPTDIR/openwhisk-client-key-whisk-system.pem" \
-passin pass:$PASSWORD \
- -subj "/C=US/ST=NY/L=Yorktown/O=OpenWhisk/CN=guest" \
- -out "$SCRIPTDIR/openwhisk-client-certificate-request.csr"
+ -subj "/C=US/ST=NY/L=Yorktown/O=OpenWhisk/CN=whisk.system" \
+ -out "$SCRIPTDIR/openwhisk-client-certificate-request-whisk-system.csr"
- echo generating self-signed client certificate
+ echo generating subject:whisk.system\'s self-signed client certificate
echo 01 > $SCRIPTDIR/openwhisk-client-ca-cert.srl
openssl x509 -req \
- -in "$SCRIPTDIR/openwhisk-client-certificate-request.csr" \
+ -in "$SCRIPTDIR/openwhisk-client-certificate-request-whisk-system.csr" \
+ -CA "$SCRIPTDIR/openwhisk-client-ca-cert.pem" \
+ -CAkey "$SCRIPTDIR/openwhisk-client-ca-key.pem" \
+ -CAserial "$SCRIPTDIR/openwhisk-client-ca-cert.srl" \
+ -passin pass:$PASSWORD \
+ -out "$SCRIPTDIR/openwhisk-client-cert-whisk-system.pem" \
+ -days 365 -sha1 -extensions v3_req
+
+ echo remove subject:whisk.system\'s client key\'s password
+ openssl rsa \
+ -in "$SCRIPTDIR/openwhisk-client-key-whisk-system.pem" \
+ -passin pass:$PASSWORD \
+ -out "$SCRIPTDIR/openwhisk-client-key-whisk-system.pem"
+
+ echo generating subject:guest\'s client key
+ openssl genrsa -aes256 -passout pass:$PASSWORD -out
"$SCRIPTDIR/openwhisk-client-key-guest.pem" 2048
+
+ echo generating subject:guest\'s client certificate csr file
+ openssl req -new \
+ -key "$SCRIPTDIR/openwhisk-client-key-guest.pem" \
+ -passin pass:$PASSWORD \
+ -subj "/C=US/ST=NY/L=Yorktown/O=OpenWhisk/CN=guest" \
+ -out "$SCRIPTDIR/openwhisk-client-certificate-request-guest.csr"
+
+ echo generating subject:guest\'s self-signed client certificate
+ openssl x509 -req \
+ -in "$SCRIPTDIR/openwhisk-client-certificate-request-guest.csr" \
-CA "$SCRIPTDIR/openwhisk-client-ca-cert.pem" \
-CAkey "$SCRIPTDIR/openwhisk-client-ca-key.pem" \
-CAserial "$SCRIPTDIR/openwhisk-client-ca-cert.srl" \
-passin pass:$PASSWORD \
- -out "$SCRIPTDIR/openwhisk-client-cert.pem" \
+ -out "$SCRIPTDIR/openwhisk-client-cert-guest.pem" \
-days 365 -sha1 -extensions v3_req
- echo remove client key\'s password
+ echo remove subject:guest\'s client key\'s password
openssl rsa \
- -in "$SCRIPTDIR/openwhisk-client-key.pem" \
+ -in "$SCRIPTDIR/openwhisk-client-key-guest.pem" \
-passin pass:$PASSWORD \
- -out "$SCRIPTDIR/openwhisk-client-key.pem"
+ -out "$SCRIPTDIR/openwhisk-client-key-guest.pem"
fi
diff --git a/ansible/roles/nginx/templates/nginx.conf.j2
b/ansible/roles/nginx/templates/nginx.conf.j2
index d8526d7628..68f681725f 100644
--- a/ansible/roles/nginx/templates/nginx.conf.j2
+++ b/ansible/roles/nginx/templates/nginx.conf.j2
@@ -58,6 +58,7 @@ http {
rewrite /(.*) /api/v1/web/${namespace}/$1 break;
}
proxy_pass http://controllers;
+ proxy_set_header X-SSL-Subject $ssl_client_s_dn;
proxy_read_timeout 70s; # 60+10 additional seconds to allow
controller to terminate request
}
diff --git a/ansible/roles/routemgmt/files/installRouteMgmt.sh
b/ansible/roles/routemgmt/files/installRouteMgmt.sh
index 63da55721f..d2a78dc7cb 100755
--- a/ansible/roles/routemgmt/files/installRouteMgmt.sh
+++ b/ansible/roles/routemgmt/files/installRouteMgmt.sh
@@ -4,7 +4,7 @@
# automatically
#
# To run this command
-# ./installRouteMgmt.sh <AUTH> <APIHOST> <NAMESPACE> <WSK_CLI>
+# ./installRouteMgmt.sh <SSL_SWITCH> <AUTH> <CERT_FILE> <KEY_FILE> <APIHOST>
<NAMESPACE> <WSK_CLI>
# AUTH, APIHOST and NAMESPACE are found in $HOME/.wskprops
# WSK_CLI="$OPENWHISK_HOME/bin/wsk"
@@ -13,13 +13,16 @@ set -x
if [ $# -eq 0 ]
then
-echo "Usage: ./installRouteMgmt.sh AUTHKEY APIHOST NAMESPACE PATH_TO_WSK_CLI"
+echo "Usage: ./installRouteMgmt.sh SSL_SWITCH AUTHKEY CERT_FILE KEY_FILE
APIHOST NAMESPACE PATH_TO_WSK_CLI"
fi
-AUTH="$1"
-APIHOST="$2"
-NAMESPACE="$3"
-WSK_CLI="$4"
+SSL_SWITCH="$1"
+AUTH="$2"
+CERT_FILE="$3"
+KEY_FILE="$4"
+APIHOST="$5"
+NAMESPACE="$6"
+WSK_CLI="$7"
WHISKPROPS_FILE="$OPENWHISK_HOME/whisk.properties"
GW_USER=`fgrep apigw.auth.user= $WHISKPROPS_FILE | cut -d'=' -f2`
@@ -33,10 +36,15 @@ if [ -f "$AUTH" ]; then
AUTH=`cat $AUTH`
fi
+AUTH="--auth $AUTH"
+if [ "$SSL_SWITCH" != "off" ]; then
+ AUTH="--cert $CERT_FILE --key $KEY_FILE"
+fi
+
export WSK_CONFIG_FILE= # override local property file to avoid namespace
clashes
echo Installing apimgmt package
-$WSK_CLI -i --apihost "$APIHOST" package update --auth "$AUTH" --shared no
"$NAMESPACE/apimgmt" \
+$WSK_CLI -i --apihost "$APIHOST" package update $AUTH --shared no
"$NAMESPACE/apimgmt" \
-a description "This package manages the gateway API configuration." \
-p gwUser "$GW_USER" \
-p gwPwd "$GW_PWD" \
@@ -49,17 +57,17 @@ zip -j
"$OPENWHISK_HOME/core/routemgmt/createApi/createApi.zip" "$OPENWHISK_HOME
zip -j "$OPENWHISK_HOME/core/routemgmt/deleteApi/deleteApi.zip"
"$OPENWHISK_HOME/core/routemgmt/deleteApi/deleteApi.js"
"$OPENWHISK_HOME/core/routemgmt/deleteApi/package.json"
"$OPENWHISK_HOME/core/routemgmt/common/utils.js"
"$OPENWHISK_HOME/core/routemgmt/common/apigw-utils.js"
echo Installing apimgmt actions
-$WSK_CLI -i --apihost "$APIHOST" action update --auth "$AUTH"
"$NAMESPACE/apimgmt/getApi" "$OPENWHISK_HOME/core/routemgmt/getApi/getApi.zip" \
+$WSK_CLI -i --apihost "$APIHOST" action update $AUTH
"$NAMESPACE/apimgmt/getApi" "$OPENWHISK_HOME/core/routemgmt/getApi/getApi.zip" \
-a description 'Retrieve the specified API configuration (in JSON format)' \
--kind nodejs:default \
-a web-export true -a final true
-$WSK_CLI -i --apihost "$APIHOST" action update --auth "$AUTH"
"$NAMESPACE/apimgmt/createApi"
"$OPENWHISK_HOME/core/routemgmt/createApi/createApi.zip" \
+$WSK_CLI -i --apihost "$APIHOST" action update $AUTH
"$NAMESPACE/apimgmt/createApi"
"$OPENWHISK_HOME/core/routemgmt/createApi/createApi.zip" \
-a description 'Create an API' \
--kind nodejs:default \
-a web-export true -a final true
-$WSK_CLI -i --apihost "$APIHOST" action update --auth "$AUTH"
"$NAMESPACE/apimgmt/deleteApi"
"$OPENWHISK_HOME/core/routemgmt/deleteApi/deleteApi.zip" \
+$WSK_CLI -i --apihost "$APIHOST" action update $AUTH
"$NAMESPACE/apimgmt/deleteApi"
"$OPENWHISK_HOME/core/routemgmt/deleteApi/deleteApi.zip" \
-a description 'Delete the API' \
--kind nodejs:default \
--a web-export true -a final true
\ No newline at end of file
+-a web-export true -a final true
diff --git a/ansible/roles/routemgmt/files/uninstallRouteMgmt.sh
b/ansible/roles/routemgmt/files/uninstallRouteMgmt.sh
index d2267eeb84..e8f988fd22 100755
--- a/ansible/roles/routemgmt/files/uninstallRouteMgmt.sh
+++ b/ansible/roles/routemgmt/files/uninstallRouteMgmt.sh
@@ -4,7 +4,7 @@
# automatically
#
# To run this command
-# ./installRouteMgmt.sh <AUTH> <APIHOST> <NAMESPACE> <WSK_CLI>
+# ./installRouteMgmt.sh <SSL_SWITCH> <AUTH> <CERT_FILE> <KEY_FILE> <APIHOST>
<NAMESPACE> <WSK_CLI>
# AUTH, APIHOST and NAMESPACE are found in $HOME/.wskprops
# WSK_CLI="$OPENWHISK_HOME/bin/wsk"
@@ -13,13 +13,16 @@ set -x
if [ $# -eq 0 ]
then
-echo "Usage: ./uninstallRouteMgmt.sh AUTHKEY APIHOST NAMESPACE PATH_TO_WSK_CLI"
+echo "Usage: ./uninstallRouteMgmt.sh SSL_SWITCH AUTHKEY CERT_FILE KEY_FILE
APIHOST NAMESPACE PATH_TO_WSK_CLI"
fi
-AUTH="$1"
-APIHOST="$2"
-NAMESPACE="$3"
-WSK_CLI="$4"
+SSL_SWITCH="$1"
+AUTH="$2"
+CERT_FILE="$3"
+KEY_FILE="$4"
+APIHOST="$5"
+NAMESPACE="$6"
+WSK_CLI="$7"
# If the auth key file exists, read the key in the file. Otherwise, take the
# first argument as the key itself.
@@ -27,18 +30,23 @@ if [ -f "$AUTH" ]; then
AUTH=`cat $AUTH`
fi
+AUTH="--auth $AUTH"
+if [ "$SSL_SWITCH" != "off" ]; then
+ AUTH="--cert $CERT_FILE --key $KEY_FILE"
+fi
+
export WSK_CONFIG_FILE= # override local property file to avoid namespace
clashes
function deleteAction
{
# The "get" command will fail if the resource does not exist, so use "set
+e" to avoid exiting the script
set +e
- $WSK_CLI -i --apihost "$APIHOST" action get --auth "$AUTH" "$1"
+ $WSK_CLI -i --apihost "$APIHOST" action get $AUTH "$1"
RC=$?
if [ $RC -eq 0 ]
then
set -e
- $WSK_CLI -i --apihost "$APIHOST" action delete --auth "$AUTH" "$1"
+ $WSK_CLI -i --apihost "$APIHOST" action delete $AUTH "$1"
fi
set -e
}
@@ -47,12 +55,12 @@ function deletePackage
{
# The "get" command will fail if the resource does not exist, so use "set
+e" to avoid exiting the script
set +e
- $WSK_CLI -i --apihost "$APIHOST" package get --auth "$AUTH" "$1" -s
+ $WSK_CLI -i --apihost "$APIHOST" package get $AUTH "$1" -s
RC=$?
if [ $RC -eq 0 ]
then
set -e
- $WSK_CLI -i --apihost "$APIHOST" package delete --auth "$AUTH" "$1"
+ $WSK_CLI -i --apihost "$APIHOST" package delete $AUTH "$1"
fi
}
diff --git a/ansible/roles/routemgmt/tasks/clean.yml
b/ansible/roles/routemgmt/tasks/clean.yml
index c9b11f8985..82fe613130 100644
--- a/ansible/roles/routemgmt/tasks/clean.yml
+++ b/ansible/roles/routemgmt/tasks/clean.yml
@@ -2,6 +2,6 @@
# Remove API Gateway route management actions.
- name: remove route management actions
- shell: ./uninstallRouteMgmt.sh {{ catalog_auth_key }} {{ groups['edge'] |
first }} {{ catalog_namespace }} {{ cli.path }} chdir="{{ openwhisk_home
}}/ansible/roles/routemgmt/files"
+ shell: ./uninstallRouteMgmt.sh {{ nginx.ssl.verify_client }} {{
catalog_auth_key }} {{ catalog_cert_file }} {{ catalog_key_file }} {{
groups['edge'] | first }} {{ catalog_namespace }} {{ cli.path }} chdir="{{
openwhisk_home }}/ansible/roles/routemgmt/files"
environment:
OPENWHISK_HOME: "{{ openwhisk_home }}"
diff --git a/ansible/roles/routemgmt/tasks/deploy.yml
b/ansible/roles/routemgmt/tasks/deploy.yml
index e6fbd44ab2..b0c25b996f 100644
--- a/ansible/roles/routemgmt/tasks/deploy.yml
+++ b/ansible/roles/routemgmt/tasks/deploy.yml
@@ -1,6 +1,6 @@
---
# Install the API Gateway route management actions.
- name: install route management actions
- shell: ./installRouteMgmt.sh {{ catalog_auth_key }} {{ groups['edge'] |
first }} {{ catalog_namespace }} {{ cli.path }} chdir="{{ openwhisk_home
}}/ansible/roles/routemgmt/files"
+ shell: ./installRouteMgmt.sh {{ nginx.ssl.verify_client }} {{
catalog_auth_key }} {{ catalog_cert_file }} {{ catalog_key_file }} {{
groups['edge'] | first }} {{ catalog_namespace }} {{ cli.path }} chdir="{{
openwhisk_home }}/ansible/roles/routemgmt/files"
environment:
OPENWHISK_HOME: "{{ openwhisk_home }}"
diff --git a/ansible/tasks/installOpenwhiskCatalog.yml
b/ansible/tasks/installOpenwhiskCatalog.yml
index 72fed21f32..3746a8fc85 100644
--- a/ansible/tasks/installOpenwhiskCatalog.yml
+++ b/ansible/tasks/installOpenwhiskCatalog.yml
@@ -29,6 +29,6 @@
version: "{{ version }}"
- name: install the catalog from the catalog location
- shell: ./installCatalog.sh {{ catalog_auth_key }} {{ api_host }} {{ cli.path
}} chdir="{{ catalog_location }}/packages"
+ shell: ./installCatalog.sh {{ nginx.ssl.verify_client }} {{ catalog_auth_key
}} {{ catalog_cert_file }} {{ catalog_key_file }} {{ api_host }} {{ cli.path }}
chdir="{{ catalog_location }}/packages"
environment:
OPENWHISK_HOME: "{{ openwhisk_home }}"
diff --git a/common/scala/src/main/scala/whisk/core/WhiskConfig.scala
b/common/scala/src/main/scala/whisk/core/WhiskConfig.scala
index 289090a183..c685f6af47 100644
--- a/common/scala/src/main/scala/whisk/core/WhiskConfig.scala
+++ b/common/scala/src/main/scala/whisk/core/WhiskConfig.scala
@@ -100,6 +100,7 @@ class WhiskConfig(
val triggerFirePerMinuteLimit = this(WhiskConfig.triggerFirePerMinuteLimit)
val actionInvokeSystemOverloadLimit =
this(WhiskConfig.actionInvokeSystemOverloadLimit)
val actionSequenceLimit = this(WhiskConfig.actionSequenceMaxLimit)
+ val sslClientVerification = this(WhiskConfig.sslClientVerification)
}
object WhiskConfig {
@@ -219,4 +220,5 @@ object WhiskConfig {
val actionInvokeConcurrentLimit = "limits.actions.invokes.concurrent"
val actionInvokeSystemOverloadLimit =
"limits.actions.invokes.concurrentInSystem"
val triggerFirePerMinuteLimit = "limits.triggers.fires.perMinute"
+ val sslClientVerification = "whisk.ssl.client.verification"
}
diff --git a/common/scala/src/main/scala/whisk/core/entity/Identity.scala
b/common/scala/src/main/scala/whisk/core/entity/Identity.scala
index 38bda8682c..599657e069 100644
--- a/common/scala/src/main/scala/whisk/core/entity/Identity.scala
+++ b/common/scala/src/main/scala/whisk/core/entity/Identity.scala
@@ -74,6 +74,53 @@ object Identity extends
MultipleReadersSingleWriterCache[Identity, DocInfo] with
})
}
+ /**
+ * Many subjects can be belonged to only one namespace
+ * Retrieves a key for namespace + subject.
+ *
+ */
+ def get(datastore: AuthStore, namespace: EntityName, subject: Subject)(
+ implicit transid: TransactionId): Future[Identity] = {
+ implicit val logger: Logging = datastore.logging
+ implicit val ec = datastore.executionContext
+ val ns = namespace.asString
+ val sbj = subject.asString
+
+ cacheLookup(ns + sbj, {
+ //Because under one namespace can have more than one subject, so
should query all subjects under this namespace.
+ list(datastore, List(ns), -1) map { list =>
+ list.length match {
+ case 0 =>
+ logger.info(this, s"$viewName:subject:[$subject]
doesn't exist on namespace:[$namespace]")
+ throw new
NoDocumentException(s"$viewName:subject:[$subject] doesn't exist on
namespace:[$namespace]")
+ case _ =>
+ list.find { obj =>
+ val Seq(JsString(id)) = obj.getFields("id")
+ id == sbj
+ } match {
+ case Some(row) => {
+ row.getFields("id", "value") match {
+ case Seq(JsString(id), JsObject(value)) =>
+ val subject = Subject(id)
+ val JsString(uuid) = value("uuid")
+ val JsString(secret) = value("key")
+ val JsString(namespace) =
value("namespace")
+ Identity(subject,
EntityName(namespace), AuthKey(UUID(uuid), Secret(secret)), Privilege.ALL)
+ case _ =>
+ logger.error(this, s"$viewName[$ns]
has malformed view '${row.compactPrint}'")
+ throw new
IllegalStateException("identities view malformed")
+ }
+ }
+ case None => {
+ logger.info(this,
s"$viewName:subject:[$subject] doesn't exist on namespace:[$namespace]")
+ throw new
NoDocumentException(s"$viewName:subject:[$subject] doesn't exist on
namespace:[$namespace]")
+ }
+ }
+ }
+ }
+ })
+ }
+
def get(datastore: AuthStore, authkey: AuthKey)(
implicit transid: TransactionId): Future[Identity] = {
implicit val logger: Logging = datastore.logging
diff --git
a/core/controller/src/main/scala/whisk/core/controller/Authenticate.scala
b/core/controller/src/main/scala/whisk/core/controller/Authenticate.scala
index ea3db36db8..e4c1a67ad6 100644
--- a/core/controller/src/main/scala/whisk/core/controller/Authenticate.scala
+++ b/core/controller/src/main/scala/whisk/core/controller/Authenticate.scala
@@ -23,23 +23,19 @@ import akka.http.scaladsl.model.headers._
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.util.Try
-
import whisk.common.Logging
import whisk.common.TransactionId
import whisk.core.database.NoDocumentException
-import whisk.core.entity.UUID
+import whisk.core.entity._
import whisk.core.entity.types.AuthStore
-import whisk.core.entity.WhiskAuthStore
-import whisk.core.entity.AuthKey
-import whisk.core.entity.Identity
-import whisk.core.entity.Secret
-import whisk.core.entity.UUID
object Authenticate {
/** Required properties for this component */
def requiredProperties = WhiskAuthStore.requiredProperties
}
+case class CertificateInfo(namespace: EntityName, subject: Subject)
+
/** A trait to validate basic auth credentials */
trait Authenticate {
protected implicit val executionContext: ExecutionContext
@@ -79,4 +75,22 @@ trait Authenticate {
Future.successful(None)
}
}
+
+ def validateCertificate(certificateInfo: Option[CertificateInfo])(implicit
transid: TransactionId): Future[Option[Identity]] = {
+ certificateInfo flatMap { certificateEntity =>
+ Try {
+ val future = Identity.get(authStore,
certificateEntity.namespace, certificateEntity.subject) map { result =>
+ Some(result)
+ } recover {
+ case _: NoDocumentException | _: IllegalArgumentException
=>
+ logging.info(this, s"authentication not valid")
+ None
+ }
+ future onFailure { case t => logging.error(this,
s"authentication error: $t") }
+ future
+ }.toOption
+ } getOrElse {
+ Future.successful(None)
+ }
+ }
}
diff --git
a/core/controller/src/main/scala/whisk/core/controller/AuthenticatedRoute.scala
b/core/controller/src/main/scala/whisk/core/controller/AuthenticatedRoute.scala
index e9b481f6db..f07566bb2c 100644
---
a/core/controller/src/main/scala/whisk/core/controller/AuthenticatedRoute.scala
+++
b/core/controller/src/main/scala/whisk/core/controller/AuthenticatedRoute.scala
@@ -19,16 +19,20 @@ package whisk.core.controller
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
-
-import akka.http.scaladsl.server.Route
+import akka.http.scaladsl.server.{AuthenticationFailedRejection, Directive1,
Route}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.server.directives._
import akka.http.scaladsl.server.directives.AuthenticationResult
import akka.http.scaladsl.model.headers._
+import
akka.http.scaladsl.server.AuthenticationFailedRejection.{CredentialsMissing,
CredentialsRejected}
+import akka.http.scaladsl.server.directives.BasicDirectives.provide
+import akka.http.scaladsl.server.directives.FutureDirectives.onSuccess
+import akka.http.scaladsl.server.directives.RouteDirectives.reject
+import whisk.common.{PrintStreamLogging, TransactionId}
+import whisk.core.WhiskConfig
+import whisk.core.entity.{EntityName, Identity, Subject}
-import whisk.common.TransactionId
-import whisk.core.entity.Identity
/** A common trait for secured routes */
trait AuthenticatedRoute {
@@ -36,6 +40,17 @@ trait AuthenticatedRoute {
/** An execution context for futures */
protected implicit val executionContext: ExecutionContext
+ /*** Auth route for basic auth and certificate auth*/
+ def authenticate(implicit transid: TransactionId) = {
+ implicit val logger = new PrintStreamLogging()
+ val config = new WhiskConfig(Map("whisk.ssl.client.verification" ->
null))
+ if (config.sslClientVerification == "off"){
+ basicAuth(validateCredentials)
+ }else{
+ certificateAuth(validateCertificate)
+ }
+ }
+
/** Creates HTTP BasicAuth handler */
def basicAuth[A](verify: Option[BasicHttpCredentials] =>
Future[Option[A]]) = {
authenticateOrRejectWithChallenge[BasicHttpCredentials, A] { creds =>
@@ -46,8 +61,44 @@ trait AuthenticatedRoute {
}
}
+
+ /** Create certificate auth handler */
+ def certificateAuth[A](verify: Option[CertificateInfo] =>
Future[Option[A]]):AuthenticationDirective[A] = {
+ val result = extract { ctx =>
+ val authHeader = ctx.request.headers.find(_.is("x-ssl-subject"))
+ val subjectHeader = authHeader flatMap {
+ case header =>
+ header.value.split(",").find(_.startsWith("CN="))
+ }
+ val subject: Option[Subject] = subjectHeader map {
+ case subject => Subject(subject.substring("CN=".length,
subject.length))
+ }
+ val namespaceHeader = ctx.request.headers.find(_.is("namespace"))
+ val certificateInfo: Option[CertificateInfo] = namespaceHeader map
{
+ case header if header.value() == "_" =>
CertificateInfo(EntityName(subject.get.asString), subject.get)
+ case header if header.value() != "_" =>
CertificateInfo(EntityName(header.value), subject.get)
+ }
+ val certificateFuture = verify(certificateInfo).map {
+ case Some(t) => AuthenticationResult.success(t)
+ case None =>
AuthenticationResult.failWithChallenge(HttpChallenges.basic("OpenWhisk secure
realm"))
+ }
+ onSuccess(certificateFuture).flatMap {
+ case Right(user) ⇒ provide(user)
+ case Left(challenge) ⇒
+ val cause = if (authHeader.isEmpty) CredentialsMissing
else CredentialsRejected
+ reject(AuthenticationFailedRejection(cause, challenge)):
Directive1[A]
+ }
+ }
+ result.flatMap { user =>
+ user
+ }
+ }
+
/** Validates credentials against database of subjects */
protected def validateCredentials(credentials:
Option[BasicHttpCredentials])(implicit transid: TransactionId):
Future[Option[Identity]]
+
+ /** Validates client certificate against database of subjects */
+ protected def validateCertificate(certificateInfo:
Option[CertificateInfo])(implicit transid: TransactionId):
Future[Option[Identity]]
}
/** A trait for authenticated routes. */
diff --git
a/core/controller/src/main/scala/whisk/core/controller/RestAPIs.scala
b/core/controller/src/main/scala/whisk/core/controller/RestAPIs.scala
index 5d4fc74f31..2703ac26c6 100644
--- a/core/controller/src/main/scala/whisk/core/controller/RestAPIs.scala
+++ b/core/controller/src/main/scala/whisk/core/controller/RestAPIs.scala
@@ -162,7 +162,7 @@ class RestAPIVersion(config: WhiskConfig, apiPath: String,
apiVersion: String)(
def routes(implicit transid: TransactionId): Route = {
prefix {
sendCorsHeaders {
- info ~ basicAuth(validateCredentials) { user =>
+ info ~ authenticate(transid) { user =>
namespaces.routes(user) ~
pathPrefix(Collection.NAMESPACES) {
actions.routes(user) ~
@@ -177,7 +177,7 @@ class RestAPIVersion(config: WhiskConfig, apiPath: String,
apiVersion: String)(
} ~ {
// web actions are distinct to separate the cors header
// and allow the actions themselves to respond to options
- basicAuth(validateCredentials) { user =>
+ authenticate(transid) { user =>
web.routes(user) ~ webexp.routes(user)
} ~ {
web.routes() ~ webexp.routes()
diff --git a/docs/cli.md b/docs/cli.md
index 92c5483eba..d0a51964f7 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -81,10 +81,11 @@ After you have configured your environment, you can begin
using the OpenWhisk CL
The CLI can be setup to use an HTTPS proxy. To setup an HTTPS proxy, an
environment variable called `HTTPS_PROXY` must be created. The variable must be
set to the address of the HTTPS proxy, and its port using the following format:
`{PROXY IP}:{PROXY PORT}`.
-## Configure the CLI to use client certificate
-The CLI has an extra level of security from client to apihost, system provides
default client certificate configuration which deployment process generated,
then you can refer to below steps to use client certificate:
-* The client certificate verification is off default, you can configure
`nginx_ssl_verify_client` to `on` or `optional` to open it for your
corresponding environment configuration.
-* Create your own client certificate instead of system provides if you want,
after created, you can configure `openwhisk_client_ca_cert` to your own ca cert
path for your corresponding environment configuration.
+## How to use CLI to pass client certificate(cert and key)
+Openwhisk provides another client certificate authentication like auth key,
openwhisk itself doens't care how to generate client certificate, it just
provides a entry point configuration to how to use it.
+* The client certificate verification is `off` default, you can configure
`nginx_ssl_verify_client` to `on` to open it, in the meantime, the auth key
verification will be invalid.
+* Create ca cert instead of system provides if you want, after created, you
can configure `openwhisk_client_ca_cert` to your own ca cert path.
+* When create your own client cert, make sure `CN` value which is saved in
cert's subject info can match corresponding user in couchdb in that namespace
which you want to access.
* Run the follwing command to pass client certificate:
```
./bin/wsk property set --cert <client_cert_path> --key <client_key_path>
diff --git a/tests/src/test/scala/common/Wsk.scala
b/tests/src/test/scala/common/Wsk.scala
index c648d9fd08..486a4b0ae3 100644
--- a/tests/src/test/scala/common/Wsk.scala
+++ b/tests/src/test/scala/common/Wsk.scala
@@ -71,8 +71,8 @@ import whisk.utils.retry
case class WskProps(
authKey: String =
WhiskProperties.readAuthKey(WhiskProperties.getAuthFileForTesting),
- cert: String =
WhiskProperties.getFileRelativeToWhiskHome("ansible/roles/nginx/files/openwhisk-client-cert.pem").getAbsolutePath,
- key: String =
WhiskProperties.getFileRelativeToWhiskHome("ansible/roles/nginx/files/openwhisk-client-key.pem").getAbsolutePath
,
+ cert: String =
WhiskProperties.getFileRelativeToWhiskHome("ansible/roles/nginx/files/openwhisk-client-cert-guest.pem").getAbsolutePath,
+ key: String =
WhiskProperties.getFileRelativeToWhiskHome("ansible/roles/nginx/files/openwhisk-client-key-guest.pem").getAbsolutePath
,
namespace: String = "_",
apiversion: String = "v1",
apihost: String = WhiskProperties.getEdgeHost,
diff --git a/tests/src/test/scala/whisk/core/cli/test/WskConfigTests.scala
b/tests/src/test/scala/whisk/core/cli/test/WskConfigTests.scala
index fbe1631adb..17cbee0824 100644
--- a/tests/src/test/scala/whisk/core/cli/test/WskConfigTests.scala
+++ b/tests/src/test/scala/whisk/core/cli/test/WskConfigTests.scala
@@ -89,7 +89,7 @@ class WskConfigTests
val stderr = wsk.cli(Seq("list") ++ wskprops.overrides, env = env,
expectedExitCode = MISUSE_EXIT).stderr
try {
stderr should include regex (s"usage[:.]")
- stderr should include("--auth is required")
+ stderr should include("--auth or (--cert and --key) is required")
} finally {
tmpwskprops.delete()
}
@@ -148,11 +148,10 @@ class WskConfigTests
val env = Map("WSK_CONFIG_FILE" ->
tmpwskprops.getAbsolutePath())
// Send request to https://<apihost>/api/v1/namespaces, wsk
client passes client certificate to nginx, nginx will
// verify it by client ca's openwhisk-client-ca-cert.pem
- val stdout = wsk.cli(Seq("property", "set", "-i", "--apihost",
wskprops.apihost, "--auth", wskprops.authKey,
+ val stdout = wsk.cli(Seq("property", "set", "-i", "--apihost",
wskprops.apihost,
"--cert", wskprops.cert, "--key", wskprops.key,
"--namespace", namespace), env = env).stdout
stdout should include(s"ok: client cert set")
stdout should include(s"ok: client key set")
- stdout should include(s"ok: whisk auth set")
stdout should include(s"ok: whisk API host set to
${wskprops.apihost}")
stdout should include(s"ok: whisk namespace set to
${namespace}")
} finally {
@@ -165,7 +164,7 @@ class WskConfigTests
try {
val namespace =
wsk.namespace.list().stdout.trim.split("\n").last
val env = Map("WSK_CONFIG_FILE" ->
tmpwskprops.getAbsolutePath())
- val thrown = the[Exception] thrownBy wsk.cli(Seq("property",
"set", "-i", "--apihost", wskprops.apihost, "--auth", wskprops.authKey,
+ val thrown = the[Exception] thrownBy wsk.cli(Seq("property",
"set", "-i", "--apihost", wskprops.apihost,
"--cert", "invalid-cert.pem", "--key", "invalid-key.pem",
"--namespace", namespace), env = env)
thrown.getMessage should include("cannot validate certificate")
} finally {
diff --git
a/tests/src/test/scala/whisk/core/controller/test/AuthenticateTests.scala
b/tests/src/test/scala/whisk/core/controller/test/AuthenticateTests.scala
index e964856f8d..1bf3572e1f 100644
--- a/tests/src/test/scala/whisk/core/controller/test/AuthenticateTests.scala
+++ b/tests/src/test/scala/whisk/core/controller/test/AuthenticateTests.scala
@@ -18,13 +18,10 @@
package whisk.core.controller.test
import scala.concurrent.Await
-
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
-
import akka.http.scaladsl.model.headers.BasicHttpCredentials
-
-import whisk.core.controller.Authenticate
+import whisk.core.controller.{Authenticate, CertificateInfo}
import whisk.core.entity._
import whisk.core.entitlement.Privilege
@@ -60,7 +57,6 @@ class AuthenticateTests extends ControllerTestCommon with
Authenticate {
val pass = BasicHttpCredentials(ns.authkey.uuid.asString,
ns.authkey.key.asString)
val user = Await.result(validateCredentials(Some(pass)),
dbOpTimeout)
user.get shouldBe Identity(subject, ns.name, ns.authkey,
Privilege.ALL)
-
// first lookup should have been from datastore
stream.toString should include regex (s"serving from datastore:
${ns.authkey.uuid.asString}")
stream.reset()
@@ -126,4 +122,61 @@ class AuthenticateTests extends ControllerTestCommon with
Authenticate {
val user = Await.result(validateCredentials(Some(pass)), dbOpTimeout)
user should be(None)
}
+
+ it should "authorize a known user using different namespaces and cache
key, and reject invalid secret for certificate auth" in {
+ implicit val tid = transid()
+ val subject = Subject()
+
+ val namespaces = Set(
+ WhiskNamespace(MakeName.next("authenticatev_tests"), AuthKey()),
+ WhiskNamespace(MakeName.next("authenticatev_tests"), AuthKey()))
+ val entry = WhiskAuth(subject, namespaces)
+ put(authStore, entry) // this test entry is reclaimed when the test
completes
+
+ // Try to login with each specific namespace
+ namespaces.foreach { ns =>
+ println(s"Trying to login to $ns")
+ val certificateInfo = CertificateInfo(ns.name, subject)
+ val user =
Await.result(validateCertificate(Some(certificateInfo)), dbOpTimeout)
+ user.get shouldBe Identity(subject, ns.name, ns.authkey,
Privilege.ALL)
+ // first lookup should have been from datastore
+ stream.toString should include regex (s"serving from datastore:
${ns.name.asString}${subject.asString}")
+ stream.reset()
+
+ // repeat query, now should be served from cache
+ val cachedUser =
Await.result(validateCertificate(Some(certificateInfo))(transid()), dbOpTimeout)
+ cachedUser.get shouldBe Identity(subject, ns.name, ns.authkey,
Privilege.ALL)
+
+ stream.toString should include regex (s"serving from cache:
${ns.name.asString}${subject.asString}")
+ stream.reset()
+ }
+ }
+
+ it should "not authorize an unknown user for certificate auth" in {
+ implicit val tid = transid()
+ val creds = WhiskAuthHelpers.newIdentity()
+ val certificateInfo = CertificateInfo(creds.namespace, creds.subject)
+ val user = Await.result(validateCertificate(Some(certificateInfo)),
dbOpTimeout)
+ user should be(None)
+ }
+
+ it should "not authorize when no user's namespace and subject are provided
for certificate auth" in {
+ implicit val tid = transid()
+ val user = Await.result(validateCertificate(None), dbOpTimeout)
+ user should be(None)
+ }
+
+ it should "not authorize when malformed namespace is provided for
certificate auth" in {
+ implicit val tid = transid()
+ val certificateInfo =
CertificateInfo(EntityName("no-exist-namespace"), Subject())
+ val user = Await.result(validateCertificate(Some(certificateInfo)),
dbOpTimeout)
+ user should be(None)
+ }
+
+ it should "not authorize when malformed namespace and subject are provided
for certificate auth" in {
+ implicit val tid = transid()
+ val certificateInfo =
CertificateInfo(EntityName("no-exist-namespace"), Subject("no-exist-subject"))
+ val user = Await.result(validateCertificate(Some(certificateInfo)),
dbOpTimeout)
+ user should be(None)
+ }
}
diff --git a/tools/cli/go-whisk-cli/commands/api.go
b/tools/cli/go-whisk-cli/commands/api.go
index bd60492ff4..05e13cc1f6 100644
--- a/tools/cli/go-whisk-cli/commands/api.go
+++ b/tools/cli/go-whisk-cli/commands/api.go
@@ -925,9 +925,11 @@ func getUserContextId() (string, error) {
if len(props["AUTH"]) > 0 {
guid = strings.Split(props["AUTH"], ":")[0]
} else {
- whisk.Debug(whisk.DbgError, "AUTH property not set in properties
file: %s\n", Properties.PropsFile)
- errStr := wski18n.T("Authorization key is not configured (--auth
is required)")
- err = whisk.MakeWskError(errors.New(errStr),
whisk.EXIT_CODE_ERR_GENERAL, whisk.DISPLAY_MSG, whisk.NO_DISPLAY_USAGE)
+ if len(props["CERT"]) == 0 || len(props["KEY"]) == 0 {
+ whisk.Debug(whisk.DbgError, "AUTH property or CERT/KEY
property also not set in properties file: %s\n", Properties.PropsFile)
+ errStr := wski18n.T("Authorization key or client certificate
is not configured (--auth or (--cert and --key) is required)")
+ err = whisk.MakeWskError(errors.New(errStr),
whisk.EXIT_CODE_ERR_GENERAL, whisk.DISPLAY_MSG, whisk.NO_DISPLAY_USAGE)
+ }
}
} else {
whisk.Debug(whisk.DbgError, "readProps(%s) failed: %s\n",
Properties.PropsFile, err)
diff --git a/tools/cli/go-whisk-cli/wski18n/resources/en_US.all.json
b/tools/cli/go-whisk-cli/wski18n/resources/en_US.all.json
index 39551d0721..539295dc3a 100644
--- a/tools/cli/go-whisk-cli/wski18n/resources/en_US.all.json
+++ b/tools/cli/go-whisk-cli/wski18n/resources/en_US.all.json
@@ -1480,8 +1480,8 @@
"translation": "Set the web action response TYPE. Possible values are
html, http, json, text, svg"
},
{
- "id": "Authorization key is not configured (--auth is required)",
- "translation": "Authorization key is not configured (--auth is required)"
+ "id": "Authorization key or client certificate is not configured (--auth
or (--cert and --key) is required)",
+ "translation": "Authorization key or client certificate is not configured
(--auth or (--cert and --key) is required)"
},
{
"id": "Specify the API output `TYPE`, either json or yaml",
diff --git a/tools/cli/go-whisk/whisk/client.go
b/tools/cli/go-whisk/whisk/client.go
index 94b78ba8c6..6195a7f78e 100644
--- a/tools/cli/go-whisk/whisk/client.go
+++ b/tools/cli/go-whisk/whisk/client.go
@@ -67,6 +67,7 @@ type Client struct {
type Config struct {
Namespace string // NOTE :: Default is "_"
+ NamespaceHeader string //Pass namespace by header when using client
certificate auth.
Cert string
Key string
AuthToken string
@@ -90,6 +91,7 @@ func NewClient(httpClient *http.Client, config *Config)
(*Client, error) {
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
}
+ config.NamespaceHeader = config.Namespace
}
}else{
tlsConfig = &tls.Config{
@@ -214,10 +216,15 @@ func (c *Client) addAuthHeader(req *http.Request,
authRequired bool) error {
Debug(DbgInfo, "Adding basic auth header; using authkey\n")
} else {
if authRequired {
- Debug(DbgError, "The required authorization key is not configured
- neither set as a property nor set via the --auth CLI argument\n")
- errStr := wski18n.T("Authorization key is not configured (--auth
is required)")
- werr := MakeWskError(errors.New(errStr), EXIT_CODE_ERR_USAGE,
DISPLAY_MSG, DISPLAY_USAGE)
- return werr
+ if c.Config.Cert == "" || c.Config.Key == "" {
+ Debug(DbgError, "The required authorization key or client
certificate is not configured - neither set as a property nor set via the
--auth or (--cert and --key)CLI argument\n")
+ errStr := wski18n.T("Authorization key or client certificate
is not configured (--auth or (--cert and --key) is required)")
+ werr := MakeWskError(errors.New(errStr), EXIT_CODE_ERR_USAGE,
DISPLAY_MSG, DISPLAY_USAGE)
+ return werr
+ }else{
+ //Pass namespace by header when using client certificate auth.
+ req.Header.Add("namespace", c.Config.NamespaceHeader)
+ }
}
}
return nil
diff --git a/tools/cli/go-whisk/wski18n/resources/en_US.all.json
b/tools/cli/go-whisk/wski18n/resources/en_US.all.json
index e473202f81..53c57f92a6 100644
--- a/tools/cli/go-whisk/wski18n/resources/en_US.all.json
+++ b/tools/cli/go-whisk/wski18n/resources/en_US.all.json
@@ -44,8 +44,8 @@
"translation": "Unable to add the HTTP authentication header: {{.err}}"
},
{
- "id": "Authorization key is not configured (--auth is required)",
- "translation": "Authorization key is not configured (--auth is required)"
+ "id": "Authorization key or client certificate is not configured (--auth
or (--cert and --key) is required)",
+ "translation": "Authorization key or client certificate is not configured
(--auth or (--cert and --key) is required)"
},
{
"id": "Command failed due to an HTTP failure",
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services