azure.go 13 KB

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