alficles commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1131438753


##########
traffic_ops/traffic_ops_golang/auth/certificate.go:
##########
@@ -0,0 +1,167 @@
+package auth
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+       "crypto/x509"
+       "encoding/pem"
+       "fmt"
+       "io/fs"
+       "io/ioutil"
+       "net/http"
+       "path/filepath"
+)
+
+// ParseCertificate takes a http.Request, pulls the (optionally) provided 
client TLS
+// certificates and attempts to verify them against the directory of provided 
Root CA
+// certificates. The Root CA certificates can be different than those utilized 
by the
+// http.Server. Returns an error if the verification process fails
+func VerifyClientCertificate(r *http.Request, rootCertsDirPath string) error {
+       // TODO: Parse client headers as alternative to TLS in the request
+
+       if err := loadRootCerts(rootCertsDirPath); err != nil {
+               return fmt.Errorf("failed to load root certificates")
+       }
+
+       if err := verifyClientRootChain(r.TLS.PeerCertificates); err != nil {
+               return fmt.Errorf("failed to verify client to root certificate 
chain")
+       }
+
+       return nil
+}
+
+func verifyClientRootChain(clientChain []*x509.Certificate) error {
+       if len(clientChain) == 0 {
+               return fmt.Errorf("empty client chain")
+       }
+
+       if rootPool == nil {
+               return fmt.Errorf("uninitialized root cert pool")
+       }
+
+       intermediateCertPool := x509.NewCertPool()
+       for _, intermediate := range clientChain[1:] {
+               intermediateCertPool.AddCert(intermediate)
+       }
+
+       opts := x509.VerifyOptions{
+               Intermediates: intermediateCertPool,
+               Roots:         rootPool,
+               KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+       }
+       _, err := clientChain[0].Verify(opts)
+       if err != nil {
+               return fmt.Errorf("failed to verify client cert chain. err: 
%w", err)
+       }
+       return nil
+}
+
+// Lazy initialized
+var rootPool *x509.CertPool
+
+func loadRootCerts(dirPath string) error {
+       // Root cert pool already populated
+       // TODO: This will prevent rolling cert renewals at runtime and will 
require a TO restart
+       // to pick up additional certificates.
+       if rootPool != nil {
+               return nil
+       }
+
+       if dirPath == "" {
+               return fmt.Errorf("empty path supplied for root cert directory")
+       }
+
+       err := filepath.WalkDir(dirPath,
+               // walk function to perform on each file in the supplied
+               // directory path for root certificiates.
+               //
+               // For each file in the directory, first check if it, too, is a 
dir. If so,
+               // return the filepath.SkipDir error to allow for it to be 
skipped without
+               // stopping the subsequent executions.
+               //
+               // If of type File, then load the PEM encoded string from the 
file and
+               // attempt to decode the PEM block into an x509 certificate. If 
successful,
+               // add that certificate to the Root Cert Pool to be used for 
verification.
+               //
+               // Must be a closure for access to the `dirPath` value
+               func(path string, file fs.DirEntry, e error) error {
+                       if e != nil {
+                               return e
+                       }
+
+                       // Skip logic if root directory
+                       if path == dirPath {
+                               return nil
+                       }
+
+                       // Don't traverse nested directories
+                       if file.IsDir() {
+                               return filepath.SkipDir
+                       }
+
+                       // Read file

Review Comment:
   This function shouldn't trust any file that is writable by a user that isn't 
it. Specifically, the group and anyone write bits mustn't be set. If they are, 
the file should be skipped and an error logged. Likewise, if the file isn't 
owned by either the current user or root, it shouldn't be trusted.



##########
traffic_ops/app/conf/cdn.conf:
##########
@@ -102,5 +103,8 @@
     },
     "cdni" : {
         "dcdn_id" : ""
-    }
+    },
+       "client_certificate_authentication" : {
+               "root_certificates_directory" : "/etc/pki/tls/certs/"

Review Comment:
   This is a problematic default. This will default to accepting certs signed 
by any of the default CAs, which is not what anyone is likely to want here. I 
would probably leave this undefined so the default "fails closed" with no 
acceptable roots.



##########
traffic_ops/traffic_ops_golang/auth/certificate.go:
##########
@@ -0,0 +1,167 @@
+package auth
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+       "crypto/x509"
+       "encoding/pem"
+       "fmt"
+       "io/fs"
+       "io/ioutil"
+       "net/http"
+       "path/filepath"
+)
+
+// ParseCertificate takes a http.Request, pulls the (optionally) provided 
client TLS
+// certificates and attempts to verify them against the directory of provided 
Root CA
+// certificates. The Root CA certificates can be different than those utilized 
by the
+// http.Server. Returns an error if the verification process fails
+func VerifyClientCertificate(r *http.Request, rootCertsDirPath string) error {
+       // TODO: Parse client headers as alternative to TLS in the request
+
+       if err := loadRootCerts(rootCertsDirPath); err != nil {
+               return fmt.Errorf("failed to load root certificates")
+       }
+
+       if err := verifyClientRootChain(r.TLS.PeerCertificates); err != nil {
+               return fmt.Errorf("failed to verify client to root certificate 
chain")
+       }
+
+       return nil
+}
+
+func verifyClientRootChain(clientChain []*x509.Certificate) error {
+       if len(clientChain) == 0 {
+               return fmt.Errorf("empty client chain")
+       }
+
+       if rootPool == nil {
+               return fmt.Errorf("uninitialized root cert pool")
+       }
+
+       intermediateCertPool := x509.NewCertPool()
+       for _, intermediate := range clientChain[1:] {
+               intermediateCertPool.AddCert(intermediate)
+       }
+
+       opts := x509.VerifyOptions{
+               Intermediates: intermediateCertPool,
+               Roots:         rootPool,
+               KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+       }
+       _, err := clientChain[0].Verify(opts)
+       if err != nil {
+               return fmt.Errorf("failed to verify client cert chain. err: 
%w", err)
+       }
+       return nil
+}
+
+// Lazy initialized
+var rootPool *x509.CertPool
+
+func loadRootCerts(dirPath string) error {
+       // Root cert pool already populated
+       // TODO: This will prevent rolling cert renewals at runtime and will 
require a TO restart
+       // to pick up additional certificates.
+       if rootPool != nil {
+               return nil
+       }
+
+       if dirPath == "" {
+               return fmt.Errorf("empty path supplied for root cert directory")
+       }
+
+       err := filepath.WalkDir(dirPath,
+               // walk function to perform on each file in the supplied
+               // directory path for root certificiates.
+               //
+               // For each file in the directory, first check if it, too, is a 
dir. If so,
+               // return the filepath.SkipDir error to allow for it to be 
skipped without
+               // stopping the subsequent executions.
+               //
+               // If of type File, then load the PEM encoded string from the 
file and
+               // attempt to decode the PEM block into an x509 certificate. If 
successful,
+               // add that certificate to the Root Cert Pool to be used for 
verification.
+               //
+               // Must be a closure for access to the `dirPath` value
+               func(path string, file fs.DirEntry, e error) error {
+                       if e != nil {
+                               return e
+                       }
+
+                       // Skip logic if root directory
+                       if path == dirPath {
+                               return nil
+                       }
+
+                       // Don't traverse nested directories
+                       if file.IsDir() {
+                               return filepath.SkipDir
+                       }
+
+                       // Read file
+                       pemBytes, err := ioutil.ReadFile(path)
+                       if err != nil {
+                               return fmt.Errorf("failed to open cert at %s. 
err: %w", path, err)
+                       }
+                       pemBlock, _ := pem.Decode(pemBytes)
+                       // Failed to decode PEM, skip file
+                       if pemBlock == nil {
+                               return nil
+                       }
+                       certificate, err := 
x509.ParseCertificate(pemBlock.Bytes)
+                       if err != nil {
+                               return fmt.Errorf("failed to parse PEM into 
x509. err: %w", err)

Review Comment:
   Do we want to fully bail on any unprocessable file? It might make sense to 
log and continue.



##########
traffic_ops/traffic_ops_golang/auth/certificate.go:
##########
@@ -0,0 +1,167 @@
+package auth
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+       "crypto/x509"
+       "encoding/pem"
+       "fmt"
+       "io/fs"
+       "io/ioutil"
+       "net/http"
+       "path/filepath"
+)
+
+// ParseCertificate takes a http.Request, pulls the (optionally) provided 
client TLS
+// certificates and attempts to verify them against the directory of provided 
Root CA
+// certificates. The Root CA certificates can be different than those utilized 
by the
+// http.Server. Returns an error if the verification process fails
+func VerifyClientCertificate(r *http.Request, rootCertsDirPath string) error {
+       // TODO: Parse client headers as alternative to TLS in the request
+
+       if err := loadRootCerts(rootCertsDirPath); err != nil {
+               return fmt.Errorf("failed to load root certificates")
+       }
+
+       if err := verifyClientRootChain(r.TLS.PeerCertificates); err != nil {
+               return fmt.Errorf("failed to verify client to root certificate 
chain")
+       }
+
+       return nil
+}
+
+func verifyClientRootChain(clientChain []*x509.Certificate) error {
+       if len(clientChain) == 0 {
+               return fmt.Errorf("empty client chain")
+       }
+
+       if rootPool == nil {
+               return fmt.Errorf("uninitialized root cert pool")
+       }
+
+       intermediateCertPool := x509.NewCertPool()
+       for _, intermediate := range clientChain[1:] {
+               intermediateCertPool.AddCert(intermediate)
+       }
+
+       opts := x509.VerifyOptions{
+               Intermediates: intermediateCertPool,
+               Roots:         rootPool,
+               KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+       }
+       _, err := clientChain[0].Verify(opts)
+       if err != nil {
+               return fmt.Errorf("failed to verify client cert chain. err: 
%w", err)
+       }
+       return nil
+}
+
+// Lazy initialized
+var rootPool *x509.CertPool
+
+func loadRootCerts(dirPath string) error {
+       // Root cert pool already populated
+       // TODO: This will prevent rolling cert renewals at runtime and will 
require a TO restart
+       // to pick up additional certificates.
+       if rootPool != nil {
+               return nil
+       }
+
+       if dirPath == "" {
+               return fmt.Errorf("empty path supplied for root cert directory")
+       }
+
+       err := filepath.WalkDir(dirPath,
+               // walk function to perform on each file in the supplied
+               // directory path for root certificiates.
+               //
+               // For each file in the directory, first check if it, too, is a 
dir. If so,
+               // return the filepath.SkipDir error to allow for it to be 
skipped without
+               // stopping the subsequent executions.
+               //
+               // If of type File, then load the PEM encoded string from the 
file and
+               // attempt to decode the PEM block into an x509 certificate. If 
successful,
+               // add that certificate to the Root Cert Pool to be used for 
verification.
+               //
+               // Must be a closure for access to the `dirPath` value
+               func(path string, file fs.DirEntry, e error) error {
+                       if e != nil {
+                               return e
+                       }
+
+                       // Skip logic if root directory
+                       if path == dirPath {
+                               return nil
+                       }
+
+                       // Don't traverse nested directories
+                       if file.IsDir() {
+                               return filepath.SkipDir
+                       }
+
+                       // Read file
+                       pemBytes, err := ioutil.ReadFile(path)
+                       if err != nil {
+                               return fmt.Errorf("failed to open cert at %s. 
err: %w", path, err)
+                       }
+                       pemBlock, _ := pem.Decode(pemBytes)
+                       // Failed to decode PEM, skip file
+                       if pemBlock == nil {
+                               return nil
+                       }
+                       certificate, err := 
x509.ParseCertificate(pemBlock.Bytes)
+                       if err != nil {
+                               return fmt.Errorf("failed to parse PEM into 
x509. err: %w", err)
+                       }
+
+                       if rootPool == nil {
+                               rootPool = x509.NewCertPool()
+                       }
+                       rootPool.AddCert(certificate)
+
+                       return nil
+               })
+       if err != nil {
+               return fmt.Errorf("failed to load root certs from path %s. err: 
%w", dirPath, err)
+       }
+
+       return nil
+}
+
+// ParseClientCertificateUID takes an x509 Certificate and loops through the 
Names in the
+// Subject. If it finds an asn.ObjectIdentifier that matches UID, it returns 
the
+// corresponding value. Otherwise returns empty string. If more than one UID 
is present,
+// the first result found to match is returned (order not guaranteed).
+func ParseClientCertificateUID(cert *x509.Certificate) string {
+
+       // Object Identifier value for UID used within LDAP
+       // LDAP OID reference: https://ldap.com/ldap-oid-reference-guide/
+       // 0.9.2342.19200300.100.1.1    uid     Attribute Type
+       // asn1.ObjectIdentifier([]int{0, 9, 2342, 19200300, 100, 1, 1})
+
+       for _, name := range cert.Subject.Names {
+               t := name.Type
+               if len(t) == 7 && t[0] == 0 && t[1] == 9 && t[2] == 2342 && 
t[3] == 19200300 && t[4] == 100 && t[5] == 1 && t[6] == 1 {
+                       return name.Value.(string)

Review Comment:
   This uses the first UID found. A certificate with multiple UIDs must be 
considered invalid.



##########
traffic_ops/traffic_ops_golang/auth/certificate.go:
##########
@@ -0,0 +1,167 @@
+package auth
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+       "crypto/x509"
+       "encoding/pem"
+       "fmt"
+       "io/fs"
+       "io/ioutil"
+       "net/http"
+       "path/filepath"
+)
+
+// ParseCertificate takes a http.Request, pulls the (optionally) provided 
client TLS
+// certificates and attempts to verify them against the directory of provided 
Root CA
+// certificates. The Root CA certificates can be different than those utilized 
by the
+// http.Server. Returns an error if the verification process fails
+func VerifyClientCertificate(r *http.Request, rootCertsDirPath string) error {
+       // TODO: Parse client headers as alternative to TLS in the request
+
+       if err := loadRootCerts(rootCertsDirPath); err != nil {
+               return fmt.Errorf("failed to load root certificates")
+       }
+
+       if err := verifyClientRootChain(r.TLS.PeerCertificates); err != nil {
+               return fmt.Errorf("failed to verify client to root certificate 
chain")
+       }
+
+       return nil
+}
+
+func verifyClientRootChain(clientChain []*x509.Certificate) error {
+       if len(clientChain) == 0 {
+               return fmt.Errorf("empty client chain")
+       }
+
+       if rootPool == nil {
+               return fmt.Errorf("uninitialized root cert pool")
+       }
+
+       intermediateCertPool := x509.NewCertPool()
+       for _, intermediate := range clientChain[1:] {
+               intermediateCertPool.AddCert(intermediate)
+       }
+
+       opts := x509.VerifyOptions{
+               Intermediates: intermediateCertPool,
+               Roots:         rootPool,
+               KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+       }
+       _, err := clientChain[0].Verify(opts)
+       if err != nil {
+               return fmt.Errorf("failed to verify client cert chain. err: 
%w", err)
+       }
+       return nil
+}
+
+// Lazy initialized
+var rootPool *x509.CertPool
+
+func loadRootCerts(dirPath string) error {
+       // Root cert pool already populated
+       // TODO: This will prevent rolling cert renewals at runtime and will 
require a TO restart
+       // to pick up additional certificates.
+       if rootPool != nil {
+               return nil
+       }
+
+       if dirPath == "" {
+               return fmt.Errorf("empty path supplied for root cert directory")
+       }
+
+       err := filepath.WalkDir(dirPath,
+               // walk function to perform on each file in the supplied
+               // directory path for root certificiates.
+               //
+               // For each file in the directory, first check if it, too, is a 
dir. If so,
+               // return the filepath.SkipDir error to allow for it to be 
skipped without
+               // stopping the subsequent executions.
+               //
+               // If of type File, then load the PEM encoded string from the 
file and
+               // attempt to decode the PEM block into an x509 certificate. If 
successful,
+               // add that certificate to the Root Cert Pool to be used for 
verification.
+               //
+               // Must be a closure for access to the `dirPath` value
+               func(path string, file fs.DirEntry, e error) error {
+                       if e != nil {
+                               return e
+                       }
+
+                       // Skip logic if root directory
+                       if path == dirPath {
+                               return nil
+                       }
+
+                       // Don't traverse nested directories
+                       if file.IsDir() {
+                               return filepath.SkipDir
+                       }
+
+                       // Read file
+                       pemBytes, err := ioutil.ReadFile(path)
+                       if err != nil {
+                               return fmt.Errorf("failed to open cert at %s. 
err: %w", path, err)
+                       }
+                       pemBlock, _ := pem.Decode(pemBytes)
+                       // Failed to decode PEM, skip file
+                       if pemBlock == nil {
+                               return nil
+                       }
+                       certificate, err := 
x509.ParseCertificate(pemBlock.Bytes)
+                       if err != nil {
+                               return fmt.Errorf("failed to parse PEM into 
x509. err: %w", err)
+                       }
+
+                       if rootPool == nil {
+                               rootPool = x509.NewCertPool()
+                       }
+                       rootPool.AddCert(certificate)
+
+                       return nil
+               })
+       if err != nil {
+               return fmt.Errorf("failed to load root certs from path %s. err: 
%w", dirPath, err)
+       }
+
+       return nil
+}
+
+// ParseClientCertificateUID takes an x509 Certificate and loops through the 
Names in the
+// Subject. If it finds an asn.ObjectIdentifier that matches UID, it returns 
the
+// corresponding value. Otherwise returns empty string. If more than one UID 
is present,
+// the first result found to match is returned (order not guaranteed).
+func ParseClientCertificateUID(cert *x509.Certificate) string {
+
+       // Object Identifier value for UID used within LDAP
+       // LDAP OID reference: https://ldap.com/ldap-oid-reference-guide/
+       // 0.9.2342.19200300.100.1.1    uid     Attribute Type
+       // asn1.ObjectIdentifier([]int{0, 9, 2342, 19200300, 100, 1, 1})
+
+       for _, name := range cert.Subject.Names {
+               t := name.Type
+               if len(t) == 7 && t[0] == 0 && t[1] == 9 && t[2] == 2342 && 
t[3] == 19200300 && t[4] == 100 && t[5] == 1 && t[6] == 1 {
+                       return name.Value.(string)
+               }
+       }
+
+       return ""

Review Comment:
   An empty string is a valid UID value and is defined to have a specific 
meaning in the blueprint. In particular, "empty UID" means that the certificate 
is authorized to impersonate users to facilitate trusted proxies, so "missing 
UID" is very different from "empty UID". Even if we haven't implemented 
impersonation yet, we should definitely not use empty as a sentinel for 
"missing".



##########
traffic_ops/traffic_ops_golang/auth/certificate.go:
##########
@@ -0,0 +1,167 @@
+package auth
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+       "crypto/x509"
+       "encoding/pem"
+       "fmt"
+       "io/fs"
+       "io/ioutil"
+       "net/http"
+       "path/filepath"
+)
+
+// ParseCertificate takes a http.Request, pulls the (optionally) provided 
client TLS
+// certificates and attempts to verify them against the directory of provided 
Root CA
+// certificates. The Root CA certificates can be different than those utilized 
by the
+// http.Server. Returns an error if the verification process fails
+func VerifyClientCertificate(r *http.Request, rootCertsDirPath string) error {
+       // TODO: Parse client headers as alternative to TLS in the request
+
+       if err := loadRootCerts(rootCertsDirPath); err != nil {
+               return fmt.Errorf("failed to load root certificates")
+       }
+
+       if err := verifyClientRootChain(r.TLS.PeerCertificates); err != nil {
+               return fmt.Errorf("failed to verify client to root certificate 
chain")
+       }
+
+       return nil
+}
+
+func verifyClientRootChain(clientChain []*x509.Certificate) error {
+       if len(clientChain) == 0 {
+               return fmt.Errorf("empty client chain")
+       }
+
+       if rootPool == nil {
+               return fmt.Errorf("uninitialized root cert pool")
+       }
+
+       intermediateCertPool := x509.NewCertPool()
+       for _, intermediate := range clientChain[1:] {
+               intermediateCertPool.AddCert(intermediate)
+       }
+
+       opts := x509.VerifyOptions{
+               Intermediates: intermediateCertPool,
+               Roots:         rootPool,
+               KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+       }
+       _, err := clientChain[0].Verify(opts)
+       if err != nil {
+               return fmt.Errorf("failed to verify client cert chain. err: 
%w", err)
+       }
+       return nil
+}
+
+// Lazy initialized
+var rootPool *x509.CertPool
+
+func loadRootCerts(dirPath string) error {
+       // Root cert pool already populated
+       // TODO: This will prevent rolling cert renewals at runtime and will 
require a TO restart
+       // to pick up additional certificates.
+       if rootPool != nil {
+               return nil
+       }
+
+       if dirPath == "" {
+               return fmt.Errorf("empty path supplied for root cert directory")
+       }
+
+       err := filepath.WalkDir(dirPath,
+               // walk function to perform on each file in the supplied
+               // directory path for root certificiates.
+               //
+               // For each file in the directory, first check if it, too, is a 
dir. If so,
+               // return the filepath.SkipDir error to allow for it to be 
skipped without
+               // stopping the subsequent executions.
+               //
+               // If of type File, then load the PEM encoded string from the 
file and
+               // attempt to decode the PEM block into an x509 certificate. If 
successful,
+               // add that certificate to the Root Cert Pool to be used for 
verification.
+               //
+               // Must be a closure for access to the `dirPath` value
+               func(path string, file fs.DirEntry, e error) error {
+                       if e != nil {
+                               return e
+                       }
+
+                       // Skip logic if root directory
+                       if path == dirPath {
+                               return nil
+                       }
+
+                       // Don't traverse nested directories
+                       if file.IsDir() {
+                               return filepath.SkipDir
+                       }
+
+                       // Read file

Review Comment:
   These permissions should be checked for the directory as well.



##########
traffic_ops/traffic_ops_golang/login/login.go:
##########
@@ -108,135 +108,187 @@ Subject: {{.InstanceName}} Password Reset Request` + 
"\r\n\r" + `
 </html>
 `))
 
+func clientCertAuthentication(w http.ResponseWriter, r *http.Request, db 
*sqlx.DB, cfg config.Config, dbCtx context.Context, cancelTx 
context.CancelFunc, form auth.PasswordForm, authenticated bool) bool {
+       // No certs provided by the client. Skip to form authentication
+       if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
+               return false
+       }
+
+       // If no configuration is set, skip to form auth
+       if cfg.ClientCertAuth == nil || len(cfg.ClientCertAuth.RootCertsDir) == 
0 {
+               return false
+       }
+
+       // Perform certificate verification to ensure it is valid against Root 
CAs
+       err := auth.VerifyClientCertificate(r, cfg.ClientCertAuth.RootCertsDir)
+       if err != nil {
+               log.Warnf("client cert auth: error attempting to verify client 
provided TLS certificate. err: %s\n", err)
+               return false
+       }
+
+       // Client provided a verified certificate. Extract UID value.
+       form.Username = 
auth.ParseClientCertificateUID(r.TLS.PeerCertificates[0])
+       if len(form.Username) == 0 {
+               log.Infoln("client cert auth: client provided certificate did 
not contain a UID object identifier or value")
+               return false
+       }
+
+       // Check if user exists locally (TODB) and has a role.
+       var blockingErr error
+       authenticated, err, blockingErr = 
auth.CheckLocalUserIsAllowed(form.Username, db, dbCtx)
+       if blockingErr != nil {
+               api.HandleErr(w, r, nil, http.StatusServiceUnavailable, nil, 
fmt.Errorf("error checking local user has role: %s", blockingErr.Error()))
+               return false
+       }
+       if err != nil {
+               log.Warnf("client cert auth: checking local user: %s\n", 
err.Error())
+       }
+
+       // Check LDAP if enabled
+       if !authenticated && cfg.LDAPEnabled {
+               _, authenticated, err = auth.LookupUserDN(form.Username, 
cfg.ConfigLDAP)
+               if err != nil {
+                       log.Warnf("Client Cert Auth: checking ldap user: %s\n", 
err.Error())
+               }
+       }
+
+       return authenticated
+}
+
+// LoginHandler first attempts to verify and parse user information from an 
optionally
+// provided client TLS certificate. If it fails at any point, it will fall 
back and
+// continue with the standard submitted form authentication.
 func LoginHandler(db *sqlx.DB, cfg config.Config) http.HandlerFunc {

Review Comment:
   This handles certificates as a replacement for uid/pass credentials, but not 
as a replacement for the mojo cookie. Given that the certificate can be 
seamlessly provided on every request, asking clients to use the login method to 
obtain a token that is then used instead of the certificate seems to create 
complexity where it isn't required. Additionally, certificates can ideally 
enable flows that do not use tokens, which prevents tokens from being stolen. 
The private key of a certificate isn't transmitted, so even if the certificate 
were leaked, it couldn't be used.



##########
traffic_ops/traffic_ops_golang/login/login.go:
##########
@@ -108,135 +108,187 @@ Subject: {{.InstanceName}} Password Reset Request` + 
"\r\n\r" + `
 </html>
 `))
 
+func clientCertAuthentication(w http.ResponseWriter, r *http.Request, db 
*sqlx.DB, cfg config.Config, dbCtx context.Context, cancelTx 
context.CancelFunc, form auth.PasswordForm, authenticated bool) bool {
+       // No certs provided by the client. Skip to form authentication
+       if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
+               return false
+       }
+
+       // If no configuration is set, skip to form auth
+       if cfg.ClientCertAuth == nil || len(cfg.ClientCertAuth.RootCertsDir) == 
0 {
+               return false
+       }
+
+       // Perform certificate verification to ensure it is valid against Root 
CAs
+       err := auth.VerifyClientCertificate(r, cfg.ClientCertAuth.RootCertsDir)
+       if err != nil {
+               log.Warnf("client cert auth: error attempting to verify client 
provided TLS certificate. err: %s\n", err)
+               return false
+       }
+
+       // Client provided a verified certificate. Extract UID value.
+       form.Username = 
auth.ParseClientCertificateUID(r.TLS.PeerCertificates[0])
+       if len(form.Username) == 0 {

Review Comment:
   As mentioned above, this will also need to change. I suspect 
ParseClientCertificateUID should return (string, error) and the error value 
checked here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to