You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@trafficcontrol.apache.org by "zrhoffman (via GitHub)" <gi...@apache.org> on 2023/03/09 18:04:02 UTC

[GitHub] [trafficcontrol] zrhoffman opened a new pull request, #7392: Traffic Ops client certificate authentication

zrhoffman opened a new pull request, #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392

   <!--
   Thank you for contributing! Please be sure to read our contribution guidelines: https://github.com/apache/trafficcontrol/blob/master/CONTRIBUTING.md
   If this closes or relates to an existing issue, please reference it using one of the following:
   
   Closes: #ISSUE
   Related: #ISSUE
   
   If this PR fixes a security vulnerability, DO NOT submit! Instead, contact
   the Apache Traffic Control Security Team at security@trafficcontrol.apache.org and follow the
   guidelines at https://apache.org/security regarding vulnerability disclosure.
   -->
   
   ## Overview
   
   (Largely reposting @tcfdev's PR description from #7110):
   
   This PR implements #6622 by adding the ability for a Traffic Ops instance to accept TLS certificates from a client request and verify them against specified Root CA's certificate as a form of login. This is not to be confused with mTLS, albeit has a similar design. Should a client _not_ send a TLS certificate as part of the request login functionality will default to standard form authentication (current implementation).
   
   ## Client
   
   The client will provide a TLS certificate (and intermediate(s)) when hitting the `/user/login` endpoint.
   
   The client will need to attach a certificate (and intermediate(s)) that was provided by the Root CA. The client certificate will need to contain a UID Relative Distinguished Name in the DN for the x509 certificate. The object identifier for this field is:
   
   `0.9.2342.19200300.100.1.1`
   
   This will result in a subject that looks something like:
   
   ```
   Subject: C=US, ST=Colorado, L=Denver, O=Apache, OU=ATC, CN=client.local/UID=userid
   ```
   
   ## Traffic Ops
   
   In `cnd.conf` there is a new section to define the location of the Root CA certificates that are used for verification.
   
   _*cdn.conf*_
   ```json
   "client_certificate_authentication" : {
       "root_certificates_directory" : "/etc/pki/tls/certs/"
   }
   ```
   
   Additionally, to enable a line must be added to the `traffic_ops_golang.tls_config` section if it exists. If this section is not present, ClientAuth will be enabled (but not required) by default.
   
   _*cdn.conf*_
   ````jsonc
   "traffic_ops_golang" : {
   // ... other configuration values
       "tls_config": {
           "MinVersion": 769,
           "ClientAuth" : 1 // <---- Enables requesting the client certificate
       }
   }
   ````
   
   Traffic Ops does not require the client TLS certificate to be present. And will not verify the client provided TLS certificates during the TLS handshake when establishing a connection. Only if the client sends a TLS certificate to the `/user/login` will it be processed. If the certificate (and intermediate(s)) provided by the client verifies correctly against the defined Root certificates, the UID field will be parsed. If there is more than 1 UID field, only the first one is accepted. Order is not guaranteed. The UID value will then be used for authentication.
   
   Should the TLS certificate authentication fail at any point, Traffic Ops will attempt to perform form value authentication (username and password) which is the current functionality. TLS client certificate authentication is not present on Oauth or Token login endpoints currently.
   
   <!-- **^ Add meaningful description above** --><hr/>
   
   ## Which Traffic Control components are affected by this PR?
   <!-- Please delete all components from this list that are NOT affected by this PR.
   Feel free to add the name of a tool or script that is affected but not on the list.
   -->
   - Documentation
   - Traffic Ops
   
   ## What is the best way to verify this PR?
   <!-- Please include here ALL the steps necessary to test your PR.
   If your PR has tests (and most should), provide the steps needed to run the tests.
   If not, please provide step-by-step instructions to test the PR manually and explain why your PR does not need tests. -->
   
   ## Unit
   
   Verify unit tests pass. Unit tests have been added to test TLS authentication. Existing unit tests ensure current default behavior continues to work as expected.
   
   ## Manual
   
   Test certificates can be created using the file located at `trafficcontrol/experimental/certificate_auth/generate_certs.go`. Running `go run generate_certs.go` will produce private keys and certificates for Root, Intermediate, and Client (Server cert/key is also created, but can be ignored since they too are used only in tests). Place the Root certificate in the directory location specified in the `cdn.conf` file.
   
   Launch a Traffic Ops instance.
   
   Ensure a user exists with appropriate permissions with the name `userid` (This can be changed in the `generate_certs.go` file if you want to use a different username).
   
   Send a request to the `user/login` Traffic Ops with the Client and Intermediate certs. For a Go client this would look something like:
   
   _client.go_ A more complete version can be found at `trafficcontrol/experimental/certificate_auth/example/client.go`
   ```go
   func main() {
   	// LoadX509KeyPair can also load certificate chain with intermediates
   	cert, _ := tls.LoadX509KeyPair("../certs/client-intermediate-chain.crt.pem", "../certs/client.key.pem")
   
   	transport := &http.Transport{
   		TLSClientConfig: &tls.Config{
   			Certificates: []tls.Certificate{cert},
   		},
   	}
   
   	client := http.Client{
   		Timeout:   time.Second * 60,
   		Transport: transport,
   	}
   
   	req, _ := http.NewRequest(
   		http.MethodPost,
   		"https://server.local:8443/api/4.0/user/login",
   		bytes.NewBufferString(""),
   	)
   
   	resp, _ := client.Do(req)
   	defer resp.Body.Close()
   
   	respBody, _ := ioutil.ReadAll(resp.Body)
   
   	fmt.Println(string(respBody)) // Verify Success
   	fmt.Println(resp.Cookies()) // Verify Cookie(s)
   }
   ```
   
   Upon success, a 200 OK status code will be returned along with the following body:
   ```json
   {
       "alerts": [
           {
               "text": "Successfully logged in.",
               "level": "success"
           }
       ]
   }
   ```
   
   Additional tests may also be performed if desired, such as sending a POST request with a username/password body and no certificate (current behavior). Or a bad cert (either malformed or not signed by the correct Root CA) with or without username/password form.
   
   
   ## PR submission checklist
   - [x] This PR has tests <!-- If not, please delete this text and explain why this PR does not need tests. -->
   - [x] This PR has documentation <!-- If not, please delete this text and explain why this PR does not need documentation. -->
   - [x] This PR has a CHANGELOG.md entry <!-- A fix for a bug from an ATC release, an improvement, or a new feature should have a changelog entry. -->
   - [x] This PR **DOES NOT FIX A SERIOUS SECURITY VULNERABILITY** (see [the Apache Software Foundation's security guidelines](https://apache.org/security) for details)
   
   <!--
   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.
   -->


-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175302294


##########
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:
   Considering a certificate with multiple UIDs as invalid in d5fc5e3401



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175297277


##########
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:
   Logging unprocessable files and continuing in ce46bf3af1



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175307431


##########
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:
   Only considering an empty string as invalid if no UID was found in d5fc5e3401.



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] alficles commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "alficles (via GitHub)" <gi...@apache.org>.
alficles commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1132779925


##########
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:
   The model I'm thinking of is the one SSH uses. Basically, if someone that isn't the owner of the process (or root, ofc) can write to the file, it shouldn't be trusted. Technically, it would also be acceptable to accept group write if the only one in the group is the owner of the process, but that's more complex. Practically... folks will see the error and `chmod 600` the file and be done with it. And that's fine, too.



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175289635


##########
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:
   I'm not a big fan of leaving it completely empty, because that make the feature less usable. Changed to `/etc/pki/tls/traffic_ops` in 3e3873e8f0, would that work?



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175295337


##########
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:
   Rejecting files that are group-writable or world-writable in deedb84aac



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1187821844


##########
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.
   
   You're right that this is a good idea, I opened #7498 for it. I'll make sure we implement it, but it should not block #7392 being accepted, IMO.



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] srijeet0406 merged pull request #7392: Traffic Ops client certificate authentication

Posted by "srijeet0406 (via GitHub)" <gi...@apache.org>.
srijeet0406 merged PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392


-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] ocket8888 commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "ocket8888 (via GitHub)" <gi...@apache.org>.
ocket8888 commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1131952932


##########
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:
   idk, personally I'd warn if the file was world-writable, but I think erroring out is totally reasonable. Probably better than my idea of what to do. But group permissions? That seems  a bit excessive; should we really be worrying about managing the permissions of a server down to that level? Depending on the OS that could just be circumvented with a simple link anyway - though granted I don't believe that's possible on CentOS or Rocky Linux which are all we support. Still, seems out-of-scope for a simple server to worry about system user group permissions.



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] ocket8888 commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "ocket8888 (via GitHub)" <gi...@apache.org>.
ocket8888 commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1134568370


##########
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:
   I just tested with openssh-client and it has no problem using my public or even private key with both group and world read and write permission bits set. I still say group-level permissions shouldn't be the concern of the web server, but being world-writable or readable is a severe enough violation of security concerns to warrant refusal, for sure.



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175292039


##########
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:
   @ocket8888 That means your security settings are lax. Try SSHing into a Rocky Linux, RHEL, or CentOS server where `~/.ssh/authorized_keys` is perms 777, it won't work.



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175302294


##########
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:
   Considering a certificate with multiple UIDs as invalid in c977b4b8a7



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175308347


##########
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:
   Returning `(string, error)` from `ParseClientCertificateUID` and chacking the error value there in d5fc5e3401



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] alficles commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "alficles (via GitHub)" <gi...@apache.org>.
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] codecov[bot] commented on pull request #7392: Traffic Ops client certificate authentication

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#issuecomment-1462539531

   # [Codecov](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#7392](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (c4f6d64) into [master](https://codecov.io/gh/apache/trafficcontrol/commit/34a601f1840b770a660405a6c50670b2f308ad8b?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (34a601f) will **increase** coverage by `0.10%`.
   > The diff coverage is `30.43%`.
   
   ```diff
   @@             Coverage Diff              @@
   ##             master    #7392      +/-   ##
   ============================================
   + Coverage     26.12%   26.22%   +0.10%     
     Complexity       98       98              
   ============================================
     Files           648      393     -255     
     Lines         76280    45776   -30504     
     Branches         90       90              
   ============================================
   - Hits          19925    12006    -7919     
   + Misses        54520    32802   -21718     
   + Partials       1835      968     -867     
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | golib_unit | `?` | |
   | grove_unit | `?` | |
   | t3c_unit | `?` | |
   | traffic_monitor_unit | `?` | |
   | traffic_ops_unit | `19.81% <30.43%> (+0.11%)` | :arrow_up: |
   | traffic_stats_unit | `?` | |
   | unit_tests | `19.81% <30.43%> (-2.74%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [traffic\_ops/traffic\_ops\_golang/auth/authorize.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-dHJhZmZpY19vcHMvdHJhZmZpY19vcHNfZ29sYW5nL2F1dGgvYXV0aG9yaXplLmdv) | `27.05% <0.00%> (ø)` | |
   | [traffic\_ops/traffic\_ops\_golang/config/config.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-dHJhZmZpY19vcHMvdHJhZmZpY19vcHNfZ29sYW5nL2NvbmZpZy9jb25maWcuZ28=) | `35.98% <ø> (ø)` | |
   | [...affic\_ops/traffic\_ops\_golang/traffic\_ops\_golang.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-dHJhZmZpY19vcHMvdHJhZmZpY19vcHNfZ29sYW5nL3RyYWZmaWNfb3BzX2dvbGFuZy5nbw==) | `0.59% <0.00%> (-0.01%)` | :arrow_down: |
   | [traffic\_ops/traffic\_ops\_golang/login/login.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-dHJhZmZpY19vcHMvdHJhZmZpY19vcHNfZ29sYW5nL2xvZ2luL2xvZ2luLmdv) | `11.27% <15.44%> (+3.18%)` | :arrow_up: |
   | [traffic\_ops/traffic\_ops\_golang/auth/certificate.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-dHJhZmZpY19vcHMvdHJhZmZpY19vcHNfZ29sYW5nL2F1dGgvY2VydGlmaWNhdGUuZ28=) | `51.00% <51.00%> (ø)` | |
   | [traffic\_monitor/cache/cache.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-dHJhZmZpY19tb25pdG9yL2NhY2hlL2NhY2hlLmdv) | | |
   | [cache-config/t3c-update/t3c-update.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y2FjaGUtY29uZmlnL3QzYy11cGRhdGUvdDNjLXVwZGF0ZS5nbw==) | | |
   | [lib/go-util/join.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bGliL2dvLXV0aWwvam9pbi5nbw==) | | |
   | [lib/go-atscfg/chkconfig.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bGliL2dvLWF0c2NmZy9jaGtjb25maWcuZ28=) | | |
   | [lib/go-atscfg/remapdotconfig.go](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bGliL2dvLWF0c2NmZy9yZW1hcGRvdGNvbmZpZy5nbw==) | | |
   | ... and [253 more](https://codecov.io/gh/apache/trafficcontrol/pull/7392?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | |
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on a diff in pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on code in PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#discussion_r1175292039


##########
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:
   @ocket8888 That means your security settings are lax. Try SSHing into a RHEL server where `~/.ssh/authorized_keys` is perms 777, it won't work.



-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#issuecomment-1520159030

   (Rebased)


-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [trafficcontrol] zrhoffman commented on pull request #7392: Traffic Ops client certificate authentication

Posted by "zrhoffman (via GitHub)" <gi...@apache.org>.
zrhoffman commented on PR #7392:
URL: https://github.com/apache/trafficcontrol/pull/7392#issuecomment-1535204249

   Rebased to get #7489


-- 
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: issues-unsubscribe@trafficcontrol.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org