-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
250 lines (226 loc) · 6.24 KB
/
Copy pathmain.go
File metadata and controls
250 lines (226 loc) · 6.24 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package main
import (
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/xml"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"sort"
"strings"
"time"
)
const doc = `Verify that each pinned domain's live TLS chain is covered by the Android Network Security Configuration declared in network_security_config.xml.`
func main() {
var (
networkSecurityConfigPath string
timeout time.Duration
)
flag.StringVar(&networkSecurityConfigPath, "network-security-config", "", "path to network_security_config.xml")
flag.DurationVar(&timeout, "timeout", 10*time.Second, "TLS dial timeout")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), doc+"\n\n")
flag.PrintDefaults()
}
flag.Parse()
pins, err := parseXML(networkSecurityConfigPath)
if err != nil {
log.Fatalf("parse %s: %v", networkSecurityConfigPath, err)
}
fmt.Printf("=== Android pins (%s) ===\n", networkSecurityConfigPath)
for _, host := range sortedHosts(pins) {
fmt.Printf("%-20s %3d\n", host, len(pins[host]))
}
failed := false
for _, domain := range sortedHosts(pins) {
if verifyDomain(domain, pins[domain], timeout) != nil {
failed = true
}
}
fmt.Println()
if failed {
fmt.Println("error : one or more domains are not covered by Android cert pinning")
os.Exit(1)
}
fmt.Println("ok : all domains are covered by Android cert pinning")
}
// verifyDomain fetches the live chain of domain and reports whether any chain
// certificate's SPKI matches one of the configured pins.
func verifyDomain(domain string, pins []string, timeout time.Duration) error {
fmt.Printf("\n=== verify %s ===\n", domain)
certs, err := fetchChain(domain, timeout)
if err != nil {
fmt.Printf("error: %v\n", err)
return err
}
hashes := make([]string, len(certs))
fmt.Printf("chain: %d certs\n", len(certs))
for i, c := range certs {
h, err := spkiHash(c)
if err != nil {
fmt.Printf("error: cert %d: %v\n", i+1, err)
return err
}
hashes[i] = h
fmt.Printf("[%d] %-12s %-45s SPKI %s\n", i+1, certKindFor(i, len(certs)), certName(c), h)
}
fmt.Println()
idx, matched := findMatchIn(hashes, pins)
status := "ok"
notes := fmt.Sprintf("%d pins; chain cert [%d] matches %s", len(pins), idx+1, matched)
if matched == "" {
status = "error"
notes = fmt.Sprintf("%d pins; no chain cert SPKI in pin-set", len(pins))
}
fmt.Printf("%-20s %-5s %s\n", domain, status, notes)
if matched == "" {
return fmt.Errorf("%s not covered by pins", domain)
}
return nil
}
// parseXML extracts, per <domain>, the SHA-256 pins from every <pin-set> in
// the Network Security Configuration.
func parseXML(path string) (map[string][]string, error) {
pins := map[string][]string{}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
dec := xml.NewDecoder(f)
domain := ""
inPinSet := false
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
switch t := tok.(type) {
case xml.StartElement:
switch t.Name.Local {
case "domain":
domain = strings.TrimSpace(readText(dec, "domain"))
case "pin-set":
inPinSet = true
case "pin":
if inPinSet && domain != "" && attr(t.Attr, "digest") == "SHA-256" {
if v := strings.TrimSpace(readText(dec, "pin")); v != "" {
pins[domain] = append(pins[domain], v)
}
}
}
case xml.EndElement:
if t.Name.Local == "domain-config" {
domain = ""
inPinSet = false
}
}
}
return pins, nil
}
// attr returns the value of the named XML attribute, or "".
func attr(attrs []xml.Attr, name string) string {
for _, a := range attrs {
if a.Name.Local == name {
return a.Value
}
}
return ""
}
// fetchChain dials the domain over TLS and returns the chain the server
// presents (leaf first), the same set openssl s_client -showcerts shows.
func fetchChain(domain string, timeout time.Duration) ([]*x509.Certificate, error) {
dialer := &net.Dialer{Timeout: timeout}
conn, err := tls.DialWithDialer(dialer, "tcp", net.JoinHostPort(domain, "443"), &tls.Config{ServerName: domain})
if err != nil {
return nil, fmt.Errorf("tls dial %s: %w", domain, err)
}
defer conn.Close()
state := conn.ConnectionState()
if len(state.PeerCertificates) == 0 {
return nil, fmt.Errorf("tls dial %s: no peer certificates", domain)
}
return state.PeerCertificates, nil
}
// spkiHash returns the base64 SHA-256 hash of the certificate's Subject Public
// Key Info (the value used by OkHttp/Cronet pinning and Android NSC pins).
func spkiHash(c *x509.Certificate) (string, error) {
der, err := x509.MarshalPKIXPublicKey(c.PublicKey)
if err != nil {
return "", err
}
sum := sha256.Sum256(der)
return base64.StdEncoding.EncodeToString(sum[:]), nil
}
// findMatchIn returns the index (within hashes) and matching pin for the first
// hash that appears in pins, or -1/"".
func findMatchIn(hashes, pins []string) (int, string) {
for i, h := range hashes {
for _, p := range pins {
if strings.TrimSpace(p) == h {
return i, p
}
}
}
return -1, ""
}
// readText consumes tokens until the end of the given element and returns the
// accumulated character data.
func readText(dec *xml.Decoder, elem string) string {
var b strings.Builder
for {
tok, err := dec.Token()
if err != nil {
return b.String()
}
if end, ok := tok.(xml.EndElement); ok && end.Name.Local == elem {
return b.String()
}
if cd, ok := tok.(xml.CharData); ok {
b.Write(cd)
}
}
}
func sortedHosts(pins map[string][]string) []string {
hosts := make([]string, 0, len(pins))
for h := range pins {
hosts = append(hosts, h)
}
sort.Strings(hosts)
return hosts
}
// certKind identifies the position of a certificate within a chain.
type certKind string
const (
certKindLeaf certKind = "leaf"
certKindIntermediate certKind = "intermediate"
certKindRoot certKind = "root"
)
// certKindFor returns the chain position of certificate i of total.
func certKindFor(i, total int) certKind {
switch {
case i == 0:
return certKindLeaf
case i == total-1 && total > 2:
return certKindRoot
default:
return certKindIntermediate
}
}
func certName(c *x509.Certificate) string {
if c.Subject.CommonName != "" {
return "CN=" + c.Subject.CommonName
}
if len(c.Subject.Organization) > 0 {
return c.Subject.Organization[0]
}
return c.Subject.String()
}