azure.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "encoding/json"
  8. "io/ioutil"
  9. "net/http"
  10. "regexp"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "github.com/smallstep/certificates/errs"
  15. "github.com/smallstep/cli/jose"
  16. )
  17. // azureOIDCBaseURL is the base discovery url for Microsoft Azure tokens.
  18. const azureOIDCBaseURL = "https://login.microsoftonline.com"
  19. // azureIdentityTokenURL is the URL to get the identity token for an instance.
  20. const azureIdentityTokenURL = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F"
  21. // azureDefaultAudience is the default audience used.
  22. const azureDefaultAudience = "https://management.azure.com/"
  23. // azureXMSMirIDRegExp is the regular expression used to parse the xms_mirid claim.
  24. // Using case insensitive as resourceGroups appears as resourcegroups.
  25. var azureXMSMirIDRegExp = regexp.MustCompile(`(?i)^/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/Microsoft.Compute/virtualMachines/([^/]+)$`)
  26. type azureConfig struct {
  27. oidcDiscoveryURL string
  28. identityTokenURL string
  29. }
  30. func newAzureConfig(tenantID string) *azureConfig {
  31. return &azureConfig{
  32. oidcDiscoveryURL: azureOIDCBaseURL + "/" + tenantID + "/.well-known/openid-configuration",
  33. identityTokenURL: azureIdentityTokenURL,
  34. }
  35. }
  36. type azureIdentityToken struct {
  37. AccessToken string `json:"access_token"`
  38. RefreshToken string `json:"refresh_token"`
  39. ClientID string `json:"client_id"`
  40. ExpiresIn int64 `json:"expires_in,string"`
  41. ExpiresOn int64 `json:"expires_on,string"`
  42. ExtExpiresIn int64 `json:"ext_expires_in,string"`
  43. NotBefore int64 `json:"not_before,string"`
  44. Resource string `json:"resource"`
  45. TokenType string `json:"token_type"`
  46. }
  47. type azurePayload struct {
  48. jose.Claims
  49. AppID string `json:"appid"`
  50. AppIDAcr string `json:"appidacr"`
  51. IdentityProvider string `json:"idp"`
  52. ObjectID string `json:"oid"`
  53. TenantID string `json:"tid"`
  54. Version string `json:"ver"`
  55. XMSMirID string `json:"xms_mirid"`
  56. }
  57. // Azure is the provisioner that supports identity tokens created from the
  58. // Microsoft Azure Instance Metadata service.
  59. //
  60. // The default audience is "https://management.azure.com/".
  61. //
  62. // If DisableCustomSANs is true, only the internal DNS and IP will be added as a
  63. // SAN. By default it will accept any SAN in the CSR.
  64. //
  65. // If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
  66. // with the same instance will be accepted. By default only the first request
  67. // will be accepted.
  68. //
  69. // Microsoft Azure identity docs are available at
  70. // https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token
  71. // and https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service
  72. type Azure struct {
  73. *base
  74. Type string `json:"type"`
  75. Name string `json:"name"`
  76. TenantID string `json:"tenantId"`
  77. ResourceGroups []string `json:"resourceGroups"`
  78. Audience string `json:"audience,omitempty"`
  79. DisableCustomSANs bool `json:"disableCustomSANs"`
  80. DisableTrustOnFirstUse bool `json:"disableTrustOnFirstUse"`
  81. Claims *Claims `json:"claims,omitempty"`
  82. claimer *Claimer
  83. config *azureConfig
  84. oidcConfig openIDConfiguration
  85. keyStore *keyStore
  86. }
  87. // GetID returns the provisioner unique identifier.
  88. func (p *Azure) GetID() string {
  89. return p.TenantID
  90. }
  91. // GetTokenID returns the identifier of the token. The default value for Azure
  92. // the SHA256 of "xms_mirid", but if DisableTrustOnFirstUse is set to true, then
  93. // it will be the token kid.
  94. func (p *Azure) GetTokenID(token string) (string, error) {
  95. jwt, err := jose.ParseSigned(token)
  96. if err != nil {
  97. return "", errors.Wrap(err, "error parsing token")
  98. }
  99. // Get claims w/out verification. We need to look up the provisioner
  100. // key in order to verify the claims and we need the issuer from the claims
  101. // before we can look up the provisioner.
  102. var claims azurePayload
  103. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  104. return "", errors.Wrap(err, "error verifying claims")
  105. }
  106. // If TOFU is disabled create return the token kid
  107. if p.DisableTrustOnFirstUse {
  108. return claims.ID, nil
  109. }
  110. sum := sha256.Sum256([]byte(claims.XMSMirID))
  111. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  112. }
  113. // GetName returns the name of the provisioner.
  114. func (p *Azure) GetName() string {
  115. return p.Name
  116. }
  117. // GetType returns the type of provisioner.
  118. func (p *Azure) GetType() Type {
  119. return TypeAzure
  120. }
  121. // GetEncryptedKey is not available in an Azure provisioner.
  122. func (p *Azure) GetEncryptedKey() (kid string, key string, ok bool) {
  123. return "", "", false
  124. }
  125. // GetIdentityToken retrieves from the metadata service the identity token and
  126. // returns it.
  127. func (p *Azure) GetIdentityToken(subject, caURL string) (string, error) {
  128. // Initialize the config if this method is used from the cli.
  129. p.assertConfig()
  130. req, err := http.NewRequest("GET", p.config.identityTokenURL, http.NoBody)
  131. if err != nil {
  132. return "", errors.Wrap(err, "error creating request")
  133. }
  134. req.Header.Set("Metadata", "true")
  135. resp, err := http.DefaultClient.Do(req)
  136. if err != nil {
  137. return "", errors.Wrap(err, "error getting identity token, are you in a Azure VM?")
  138. }
  139. defer resp.Body.Close()
  140. b, err := ioutil.ReadAll(resp.Body)
  141. if err != nil {
  142. return "", errors.Wrap(err, "error reading identity token response")
  143. }
  144. if resp.StatusCode >= 400 {
  145. return "", errors.Errorf("error getting identity token: status=%d, response=%s", resp.StatusCode, b)
  146. }
  147. var identityToken azureIdentityToken
  148. if err := json.Unmarshal(b, &identityToken); err != nil {
  149. return "", errors.Wrap(err, "error unmarshaling identity token response")
  150. }
  151. return identityToken.AccessToken, nil
  152. }
  153. // Init validates and initializes the Azure provisioner.
  154. func (p *Azure) Init(config Config) (err error) {
  155. switch {
  156. case p.Type == "":
  157. return errors.New("provisioner type cannot be empty")
  158. case p.Name == "":
  159. return errors.New("provisioner name cannot be empty")
  160. case p.TenantID == "":
  161. return errors.New("provisioner tenantId cannot be empty")
  162. case p.Audience == "": // use default audience
  163. p.Audience = azureDefaultAudience
  164. }
  165. // Initialize config
  166. p.assertConfig()
  167. // Update claims with global ones
  168. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  169. return err
  170. }
  171. // Decode and validate openid-configuration endpoint
  172. if err := getAndDecode(p.config.oidcDiscoveryURL, &p.oidcConfig); err != nil {
  173. return err
  174. }
  175. if err := p.oidcConfig.Validate(); err != nil {
  176. return errors.Wrapf(err, "error parsing %s", p.config.oidcDiscoveryURL)
  177. }
  178. // Get JWK key set
  179. if p.keyStore, err = newKeyStore(p.oidcConfig.JWKSetURI); err != nil {
  180. return err
  181. }
  182. return nil
  183. }
  184. // authorizeToken returns the claims, name, group, error.
  185. func (p *Azure) authorizeToken(token string) (*azurePayload, string, string, error) {
  186. jwt, err := jose.ParseSigned(token)
  187. if err != nil {
  188. return nil, "", "", errs.Wrap(http.StatusUnauthorized, err, "azure.authorizeToken; error parsing azure token")
  189. }
  190. if len(jwt.Headers) == 0 {
  191. return nil, "", "", errs.Unauthorized("azure.authorizeToken; azure token missing header")
  192. }
  193. var found bool
  194. var claims azurePayload
  195. keys := p.keyStore.Get(jwt.Headers[0].KeyID)
  196. for _, key := range keys {
  197. if err := jwt.Claims(key.Public(), &claims); err == nil {
  198. found = true
  199. break
  200. }
  201. }
  202. if !found {
  203. return nil, "", "", errs.Unauthorized("azure.authorizeToken; cannot validate azure token")
  204. }
  205. if err := claims.ValidateWithLeeway(jose.Expected{
  206. Audience: []string{p.Audience},
  207. Issuer: p.oidcConfig.Issuer,
  208. Time: time.Now(),
  209. }, 1*time.Minute); err != nil {
  210. return nil, "", "", errs.Wrap(http.StatusUnauthorized, err, "azure.authorizeToken; failed to validate azure token payload")
  211. }
  212. // Validate TenantID
  213. if claims.TenantID != p.TenantID {
  214. return nil, "", "", errs.Unauthorized("azure.authorizeToken; azure token validation failed - invalid tenant id claim (tid)")
  215. }
  216. re := azureXMSMirIDRegExp.FindStringSubmatch(claims.XMSMirID)
  217. if len(re) != 4 {
  218. return nil, "", "", errs.Unauthorized("azure.authorizeToken; error parsing xms_mirid claim - %s", claims.XMSMirID)
  219. }
  220. group, name := re[2], re[3]
  221. return &claims, name, group, nil
  222. }
  223. // AuthorizeSign validates the given token and returns the sign options that
  224. // will be used on certificate creation.
  225. func (p *Azure) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  226. _, name, group, err := p.authorizeToken(token)
  227. if err != nil {
  228. return nil, errs.Wrap(http.StatusInternalServerError, err, "azure.AuthorizeSign")
  229. }
  230. // Filter by resource group
  231. if len(p.ResourceGroups) > 0 {
  232. var found bool
  233. for _, g := range p.ResourceGroups {
  234. if g == group {
  235. found = true
  236. break
  237. }
  238. }
  239. if !found {
  240. return nil, errs.Unauthorized("azure.AuthorizeSign; azure token validation failed - invalid resource group")
  241. }
  242. }
  243. // Enforce known common name and default DNS if configured.
  244. // By default we'll accept the CN and SANs in the CSR.
  245. // There's no way to trust them other than TOFU.
  246. var so []SignOption
  247. if p.DisableCustomSANs {
  248. // name will work only inside the virtual network
  249. so = append(so, commonNameValidator(name))
  250. so = append(so, dnsNamesValidator([]string{name}))
  251. }
  252. return append(so,
  253. // modifiers / withOptions
  254. newProvisionerExtensionOption(TypeAzure, p.Name, p.TenantID),
  255. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  256. // validators
  257. defaultPublicKeyValidator{},
  258. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  259. ), nil
  260. }
  261. // AuthorizeRenew returns an error if the renewal is disabled.
  262. // NOTE: This method does not actually validate the certificate or check it's
  263. // revocation status. Just confirms that the provisioner that created the
  264. // certificate was configured to allow renewals.
  265. func (p *Azure) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  266. if p.claimer.IsDisableRenewal() {
  267. return errs.Unauthorized("azure.AuthorizeRenew; renew is disabled for azure provisioner %s", p.GetID())
  268. }
  269. return nil
  270. }
  271. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  272. func (p *Azure) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  273. if !p.claimer.IsSSHCAEnabled() {
  274. return nil, errs.Unauthorized("azure.AuthorizeSSHSign; sshCA is disabled for provisioner %s", p.GetID())
  275. }
  276. _, name, _, err := p.authorizeToken(token)
  277. if err != nil {
  278. return nil, errs.Wrap(http.StatusInternalServerError, err, "azure.AuthorizeSSHSign")
  279. }
  280. signOptions := []SignOption{
  281. // set the key id to the token subject
  282. sshCertKeyIDModifier(name),
  283. }
  284. // Default to host + known hostnames
  285. defaults := SSHOptions{
  286. CertType: SSHHostCert,
  287. Principals: []string{name},
  288. }
  289. // Validate user options
  290. signOptions = append(signOptions, sshCertOptionsValidator(defaults))
  291. // Set defaults if not given as user options
  292. signOptions = append(signOptions, sshCertDefaultsModifier(defaults))
  293. return append(signOptions,
  294. // Set the default extensions.
  295. &sshDefaultExtensionModifier{},
  296. // Set the validity bounds if not set.
  297. &sshDefaultDuration{p.claimer},
  298. // Validate public key
  299. &sshDefaultPublicKeyValidator{},
  300. // Validate the validity period.
  301. &sshCertValidityValidator{p.claimer},
  302. // Require all the fields in the SSH certificate
  303. &sshCertDefaultValidator{},
  304. ), nil
  305. }
  306. // assertConfig initializes the config if it has not been initialized
  307. func (p *Azure) assertConfig() {
  308. if p.config == nil {
  309. p.config = newAzureConfig(p.TenantID)
  310. }
  311. }