-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
secure.go
140 lines (117 loc) · 3.93 KB
/
secure.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// This file is part of the Smart Home
// Program complex distribution https://github.com/e154/smart-home
// Copyright (C) 2016-2023, Filippov Alex
//
// This library is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library. If not, see
// <https://www.gnu.org/licenses/>.
package alexa
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// HTTPError is a convenience method for logging a message and writing the provided error message
// and error code to the HTTP response.
func HTTPError(w http.ResponseWriter, logMsg string, err string, errCode int) {
if logMsg != "" {
log.Error(logMsg)
}
http.Error(w, err, errCode)
}
// IsValidAlexaRequest handles all the necessary steps to validate that an incoming http.Request has actually come from
// the Server service. If an error occurs during the validation process, an http.Error will be written to the provided http.ResponseWriter.
// The required steps for request validation can be found on this page:
// --insecure-skip-verify flag will disable all validations
// https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/developing-an-alexa-skill-as-a-web-service#hosting-a-custom-skill-as-a-web-service
func IsValidAlexaRequest(w http.ResponseWriter, r *http.Request) bool {
certURL := r.Header.Get("SignatureCertChainUrl")
// Verify certificate URL
if !verifyCertURL(certURL) {
HTTPError(w, "Invalid cert URL: "+certURL, "Not Authorized", 401)
return false
}
// Fetch certificate data
certContents, err := readCert(certURL)
if err != nil {
HTTPError(w, err.Error(), "Not Authorized", 401)
return false
}
// Decode certificate data
block, _ := pem.Decode(certContents)
if block == nil {
HTTPError(w, "Failed to parse certificate PEM.", "Not Authorized", 401)
return false
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
HTTPError(w, err.Error(), "Not Authorized", 401)
return false
}
// Check the certificate date
if time.Now().Unix() < cert.NotBefore.Unix() || time.Now().Unix() > cert.NotAfter.Unix() {
HTTPError(w, "Amazon certificate expired.", "Not Authorized", 401)
return false
}
// Check the certificate alternate names
foundName := false
for _, altName := range cert.Subject.Names {
if altName.Value == "echo-api.amazon.com" {
foundName = true
}
}
if !foundName {
HTTPError(w, "Amazon certificate invalid.", "Not Authorized", 401)
return false
}
return true
}
func readCert(certURL string) ([]byte, error) {
certPool, err := x509.SystemCertPool()
if err != nil || certPool == nil {
log.Error("Can't open system cert pools")
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: certPool, InsecureSkipVerify: insecureSkipVerify},
}
hc := &http.Client{Timeout: 2 * time.Second, Transport: tr}
cert, err := hc.Get(certURL)
if err != nil {
return nil, errors.New("could not download Amazon cert file: " + err.Error())
}
defer cert.Body.Close()
certContents, err := io.ReadAll(cert.Body)
if err != nil {
return nil, errors.New("could not read Amazon cert file: " + err.Error())
}
return certContents, nil
}
func verifyCertURL(path string) bool {
link, _ := url.Parse(path)
if link.Scheme != "https" {
return false
}
if link.Host != "s3.amazonaws.com" && link.Host != "s3.amazonaws.com:443" {
return false
}
if !strings.HasPrefix(link.Path, "/echo.api/") {
return false
}
return true
}