-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
164 lines (135 loc) · 5.37 KB
/
main.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"github.com/yangl900/canipull/pkg/authorizer"
"github.com/yangl900/canipull/pkg/utils"
az "github.com/Azure/go-autorest/autorest/azure"
"github.com/yangl900/canipull/pkg/exitcode"
"github.com/yangl900/canipull/pkg/log"
"k8s.io/legacy-cloud-providers/azure"
flag "github.com/spf13/pflag"
)
const (
DefaultAzureCfgPath string = "/etc/kubernetes/azure.json"
)
var (
logLevel *uint = flag.UintP("verbose", "v", 2, "output verbosity level.")
configPath *string = flag.String("config", "", "the azure.json config file path.")
)
func main() {
flag.Parse()
if len(flag.Args()) != 1 {
fmt.Println("No ACR input. Expect `canipull myacr.azurecr.io`.")
return
}
ctx := log.WithLogLevel(context.Background(), *logLevel)
acr := flag.Args()[0]
logger := log.FromContext(ctx)
if _, err := net.LookupHost(acr); err != nil {
logger.V(2).Info("Checking host name resolution (%s): FAILED", acr)
logger.V(2).Info("Failed to resolve specified fqdn %s: %s", acr, err)
os.Exit(exitcode.DNSResolutionFailure)
}
logger.V(2).Info("Checking host name resolution (%s): SUCCEEDED", acr)
cname, err := net.LookupCNAME(acr)
if err != nil {
logger.V(2).Info("Checking CNAME (%s): FAILED", acr)
logger.V(2).Info("Failed to get CNAME of the ACR: %s", err)
os.Exit(exitcode.DNSResolutionFailure)
}
logger.V(2).Info("Canonical name for ACR (%s): %s", acr, cname)
acrLocation := strings.Split(cname, ".")[1]
logger.V(2).Info("ACR location: %s", acrLocation)
azConfigPath := *configPath
if *configPath == "" {
azConfigPath = DefaultAzureCfgPath
}
logger.V(6).Info("Loading azure.json file from %s", azConfigPath)
if _, err := os.Stat(azConfigPath); err != nil {
logger.V(2).Info("Failed to load azure.json. Are you running inside Kubernetes on Azure? \n")
os.Exit(exitcode.AzureConfigNotFound)
}
var cfg azure.Config
configBytes, err := ioutil.ReadFile(azConfigPath)
if err != nil {
logger.V(2).Info("Failed to read azure.json file: %s \n", err)
os.Exit(exitcode.AzureConfigReadFailure)
}
if err := json.Unmarshal(configBytes, &cfg); err != nil {
logger.V(2).Info("Failed to read azure.json file: %s", err)
os.Exit(exitcode.AzureConfigUnmarshalFailure)
}
if !utils.LocationEquals(acrLocation, cfg.Location) {
logger.V(2).Info("Checking ACR location matches cluster location: FAILED")
logger.V(2).Info("ACR location '%s' does not match your cluster location '%s'. This may result in slow image pulls and extra cost.", acrLocation, cfg.Location)
}
if cfg.AADClientID == "msi" && cfg.AADClientSecret == "msi" {
logger.V(2).Info("Checking managed identity...")
os.Exit(validateMsiAuth(ctx, acr, cfg, logger))
return
}
logger.V(4).Info("The cluster uses service principal.")
os.Exit(validateServicePrincipalAuth(ctx, acr, cfg, logger))
}
func validateMsiAuth(ctx context.Context, acr string, cfg azure.Config, logger *log.Logger) int {
logger.V(6).Info("Cluster cloud name: %s", cfg.Cloud)
env, err := az.EnvironmentFromName(cfg.Cloud)
if err != nil {
logger.V(2).Info("Unknown Azure cloud name: %s", cfg.Cloud)
return exitcode.AzureCloudUnknown
}
logger.V(2).Info("Kubelet managed identity client ID: %s", cfg.UserAssignedIdentityID)
tr := authorizer.NewTokenRetriever(env.ActiveDirectoryEndpoint)
token, err := tr.AcquireARMTokenMSI(ctx, cfg.UserAssignedIdentityID)
if err != nil {
logger.V(2).Info("Validating managed identity existance: FAILED")
logger.V(2).Info("Getting managed identity token failed with: %s", err)
return exitcode.ServicePrincipalCredentialInvalid
}
logger.V(2).Info("Validating managed identity existance: SUCCEEDED")
logger.V(9).Info("ARM access token: %s", token)
te := authorizer.NewTokenExchanger()
acrToken, err := te.ExchangeACRAccessToken(token, acr)
if err != nil {
logger.V(2).Info("Validating image pull permission: FAILED")
logger.V(2).Info("ACR %s rejected token exchange: %s", acr, err)
return exitcode.MissingImagePullPermision
}
logger.V(2).Info("Validating image pull permission: SUCCEEDED")
logger.V(9).Info("ACR access token: %s", acrToken)
logger.V(2).Info("\nYour cluster can pull images from %s!", acr)
return 0
}
func validateServicePrincipalAuth(ctx context.Context, acr string, cfg azure.Config, logger *log.Logger) int {
env, err := az.EnvironmentFromName(cfg.Cloud)
if err != nil {
logger.V(2).Info("Unknown Azure cloud name: %s", cfg.Cloud)
return exitcode.AzureCloudUnknown
}
tr := authorizer.NewTokenRetriever(env.ActiveDirectoryEndpoint)
token, err := tr.AcquireARMTokenSP(ctx, cfg.AADClientID, cfg.AADClientSecret, cfg.TenantID)
if err != nil {
logger.V(2).Info("Validating service principal credential: FAILED")
logger.V(2).Info("Sign in to AAD failed with: %s", err)
return exitcode.ServicePrincipalCredentialInvalid
}
logger.V(2).Info("Validating service principal credential: SUCCEEDED")
logger.V(9).Info("ARM access token: %s", token)
te := authorizer.NewTokenExchanger()
acrToken, err := te.ExchangeACRAccessToken(token, acr)
if err != nil {
logger.V(2).Info("Validating image pull permission: FAILED")
logger.V(2).Info("ACR %s rejected token exchange: %s", acr, err)
return exitcode.MissingImagePullPermision
}
logger.V(2).Info("Validating image pull permission: SUCCEEDED")
logger.V(9).Info("ACR access token: %s", acrToken)
logger.V(2).Info("\nYour cluster can pull images from %s!", acr)
return 0
}