// Challenge requests a challenge from the server running at serverAddr, which
// should be a host name or of the hostname:port form, and then fulfills that challenge.
976596
func (cl *Client) Challenge(serverAddr string) error {
	if err := cl.listenSelfCheck(serverAddr); err != nil {
		return err
	}
	return cl.challenge(serverAddr)
}
472054
func (chal Challenge) HTTP(accountKey interface{}) (urlPath, resource string, err error) {
	if chal.Type != ChallengeHTTP {
		return "", "", fmt.Errorf("challenge type is %s not %s", chal.Type, ChallengeHTTP)
	}

	urlPath = path.Join("/.well-known/acme-challenge", chal.Token)
	resource, err = keyAuth(accountKey, chal.Token)
	return
}
403585
func ProcessChallenge(challengeMessageData []byte, user, password string) ([]byte, error) {
	if user == "" && password == "" {
		return nil, errors.New("Anonymous authentication not supported")
	}

	var cm challengeMessage
	if err := cm.UnmarshalBinary(challengeMessageData); err != nil {
		return nil, err
	}

	if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATELMKEY) {
		return nil, errors.New("Only NTLM v2 is supported, but server requested v1 (NTLMSSP_NEGOTIATE_LM_KEY)")
	}
	if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATEKEYEXCH) {
		return nil, errors.New("Key exchange requested but not supported (NTLMSSP_NEGOTIATE_KEY_EXCH)")
	}

	am := authenicateMessage{
		UserName:       user,
		TargetName:     cm.TargetName,
		NegotiateFlags: cm.NegotiateFlags,
	}

	timestamp := cm.TargetInfo[avIDMsvAvTimestamp]
	if timestamp == nil { // no time sent, take current time
		ft := uint64(time.Now().UnixNano()) / 100
		ft += 116444736000000000 // add time between unix & windows offset
		timestamp = make([]byte, 8)
		binary.LittleEndian.PutUint64(timestamp, ft)
	}

	clientChallenge := make([]byte, 8)
	rand.Reader.Read(clientChallenge)

	ntlmV2Hash := getNtlmV2Hash(password, user, cm.TargetName)

	am.NtChallengeResponse = computeNtlmV2Response(ntlmV2Hash,
		cm.ServerChallenge[:], clientChallenge, timestamp, cm.TargetInfoRaw)

	if cm.TargetInfoRaw == nil {
		am.LmChallengeResponse = computeLmV2Response(ntlmV2Hash,
			cm.ServerChallenge[:], clientChallenge)
	}

	return am.MarshalBinary()
}
720512
func (va *ValidationAuthorityImpl) PerformValidation(ctx context.Context, domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) {
	logEvent := verificationRequestEvent{
		ID:        authz.ID,
		Requester: authz.RegistrationID,
		Hostname:  domain,
	}
	vStart := va.clk.Now()

	var remoteProbs chan *probs.ProblemDetails
	if remoteVACount := len(va.remoteVAs); remoteVACount > 0 {
		remoteProbs = make(chan *probs.ProblemDetails, remoteVACount)
		go va.performRemoteValidation(ctx, domain, challenge, authz, remoteProbs)
	}

	records, prob := va.validate(ctx, core.AcmeIdentifier{Type: "dns", Value: domain}, challenge, authz)
	challenge.ValidationRecord = records

	// Check for malformed ValidationRecords
	if !challenge.RecordsSane() && prob == nil {
		prob = probs.ServerInternal("Records for validation failed sanity check")
	}

	var problemType string
	if prob != nil {
		problemType = string(prob.Type)
		challenge.Status = core.StatusInvalid
		challenge.Error = prob
		logEvent.Error = prob.Error()
	} else if remoteProbs != nil {
		if !features.Enabled(features.EnforceMultiVA) && features.Enabled(features.MultiVAFullResults) {
			// If we're not going to enforce multi VA but we are logging the
			// differentials then collect and log the remote results in a separate go
			// routine to avoid blocking the primary VA.
			go func() {
				_ = va.processRemoteResults(domain, string(challenge.Type), prob, remoteProbs, len(va.remoteVAs))
			}()
		} else if features.Enabled(features.EnforceMultiVA) {
			remoteProb := va.processRemoteResults(domain, string(challenge.Type), prob, remoteProbs, len(va.remoteVAs))
			if remoteProb != nil {
				prob = remoteProb
				challenge.Status = core.StatusInvalid
				challenge.Error = remoteProb
				logEvent.Error = remoteProb.Error()
				va.log.Infof("Validation failed due to remote failures: identifier=%v err=%s",
					domain, remoteProb)
				va.metrics.remoteValidationFailures.Inc()
			} else {
				challenge.Status = core.StatusValid
			}
		}
	} else {
		challenge.Status = core.StatusValid
	}

	logEvent.Challenge = challenge

	validationLatency := time.Since(vStart)
	logEvent.ValidationLatency = validationLatency.Round(time.Millisecond).Seconds()

	va.metrics.validationTime.With(prometheus.Labels{
		"type":        string(challenge.Type),
		"result":      string(challenge.Status),
		"problemType": problemType,
	}).Observe(validationLatency.Seconds())

	va.log.AuditObject("Validation result", logEvent)
	va.log.Infof("Validations: %+v", authz)

	// Try to marshal the validation results and prob (if any) to protocol
	// buffers. We log at this layer instead of leaving it up to gRPC because gRPC
	// doesn't log the actual contents that failed to marshal, making it hard to
	// figure out what's broken.
	if _, err := bgrpc.ValidationResultToPB(records, prob); err != nil {
		va.log.Errf(
			"failed to marshal records %#v and prob %#v to protocol buffer: %v",
			records, prob, err)
	}

	if prob == nil {
		// This is necessary because if we just naively returned prob, it would be a
		// non-nil interface value containing a nil pointer, rather than a nil
		// interface value. See, e.g.
		// https://stackoverflow.com/questions/29138591/hiding-nil-values-understanding-why-golang-fails-here
		return records, nil
	}

	return records, prob
}
576568
func (w *HTTPProvider) Present(domain, token, keyAuth string) error {
	var err error

	challengeFilePath := filepath.Join(w.path, http01.ChallengePath(token))
	err = os.MkdirAll(filepath.Dir(challengeFilePath), 0755)
	if err != nil {
		return fmt.Errorf("could not create required directories in webroot for HTTP challenge -> %v", err)
	}

	err = ioutil.WriteFile(challengeFilePath, []byte(keyAuth), 0644)
	if err != nil {
		return fmt.Errorf("could not write file in webroot for HTTP challenge -> %v", err)
	}

	return nil
}
312009
func NewChallenge(appID string, trustedFacets []string) (*Challenge, error) {
	challenge := make([]byte, 32)
	n, err := rand.Read(challenge)
	if err != nil {
		return nil, err
	}
	if n != 32 {
		return nil, errors.New("u2f: unable to generate random bytes")
	}

	var c Challenge
	c.Challenge = challenge
	c.Timestamp = time.Now()
	c.AppID = appID
	c.TrustedFacets = trustedFacets
	return &c, nil
}
1072099
func (s *ProviderServer) Present(domain, token, keyAuth string) error {
	if s.port == "" {
		s.port = "80"
	}

	var err error
	s.listener, err = net.Listen("tcp", s.GetAddress())
	if err != nil {
		return fmt.Errorf("could not start HTTP server for challenge -> %v", err)
	}

	s.done = make(chan bool)
	go s.serve(domain, token, keyAuth)
	return nil
}
675383
func (pc PAConfig) CheckChallenges() error {
	if len(pc.Challenges) == 0 {
		return errors.New("empty challenges map in the Policy Authority config is not allowed")
	}
	for name := range pc.Challenges {
		if !core.ValidChallenge(name) {
			return fmt.Errorf("Invalid challenge in PA config: %s", name)
		}
	}
	return nil
}
891719
func (ra *RegistrationAuthorityImpl) createPendingAuthz(ctx context.Context, reg int64, identifier core.AcmeIdentifier, v2 bool) (*corepb.Authorization, error) {
	expires := ra.clk.Now().Add(ra.pendingAuthorizationLifetime).Truncate(time.Second).UnixNano()
	status := string(core.StatusPending)
	authz := &corepb.Authorization{
		Identifier:     &identifier.Value,
		RegistrationID: &reg,
		Status:         &status,
		Expires:        &expires,
		V2:             &v2,
	}

	// Create challenges. The WFE will update them with URIs before sending them out.
	challenges, err := ra.PA.ChallengesFor(identifier)
	if err != nil {
		// The only time ChallengesFor errors it is a fatal configuration error
		// where challenges required by policy for an identifier are not enabled. We
		// want to treat this as an internal server error.
		return nil, berrors.InternalServerError(err.Error())
	}
	// Check each challenge for sanity.
	for _, challenge := range challenges {
		if err := challenge.CheckConsistencyForClientOffer(); err != nil {
			// berrors.InternalServerError because we generated these challenges, they should
			// be OK.
			err = berrors.InternalServerError("challenge didn't pass sanity check: %+v", challenge)
			return nil, err
		}
		challPB, err := bgrpc.ChallengeToPB(challenge)
		if err != nil {
			return nil, err
		}
		authz.Challenges = append(authz.Challenges, challPB)
	}
	return authz, nil
}
1305598
func (r *PEXReactor) RequestAddrs(p Peer) {
	r.Logger.Debug("Request addrs", "from", p)
	id := string(p.ID())
	if r.requestsSent.Has(id) {
		return
	}
	r.requestsSent.Set(id, struct{}{})
	p.Send(PexChannel, cdc.MustMarshalBinaryBare(&pexRequestMessage{}))
}
1199662
func InitServerEngine(port int, serverEngine string) {
	address := HTTPAddr
	if address == "" {
		address = "localhost"
	}
	if port == 0 {
		port = HTTPPort
	}

	var network = "tcp"
	var localAddress string

	// If the port is zero, treat the address as a fully qualified local address.
	// This address must be prefixed with the network type followed by a colon,
	// e.g. unix:/tmp/app.socket or tcp6:::1 (equivalent to tcp6:0:0:0:0:0:0:0:1)
	if port == 0 {
		parts := strings.SplitN(address, ":", 2)
		network = parts[0]
		localAddress = parts[1]
	} else {
		localAddress = address + ":" + strconv.Itoa(port)
	}

	if engineLoader, ok := serverEngineMap[serverEngine]; !ok {
		panic("Server Engine " + serverEngine + " Not found")
	} else {
		CurrentEngine = engineLoader()
		serverLogger.Debug("InitServerEngine: Found server engine and invoking", "name", CurrentEngine.Name())
		ServerEngineInit = &EngineInit{
			Address:  localAddress,
			Network:  network,
			Port:     port,
			Callback: handleInternal,
		}
	}
	AddInitEventHandler(CurrentEngine.Event)
}
732027
func (idp *IDP) NewChallenge(ctx context.Context, r *http.Request, user string) (challenge *Challenge, err error) {
	tokenStr := r.FormValue("challenge")
	if tokenStr == "" {
		// No challenge token
		err = ErrorBadRequest
		return
	}

	token, err := idp.getChallengeToken(tokenStr)
	if err != nil {
		// Most probably, token can't be verified or parsed
		return
	}
	claims := token.Claims.(jwt.MapClaims)

	challenge = new(Challenge)
	challenge.Expires = time.Unix(int64(claims["exp"].(float64)), 0)
	if challenge.Expires.Before(time.Now()) {
		challenge = nil
		err = ErrorChallengeExpired
		return
	}

	// Get data from the challenge jwt
	challenge.Client, err = idp.getClient(ctx, claims["aud"].(string))
	if err != nil {
		return nil, err
	}

	challenge.Redirect = claims["redir"].(string)
	challenge.JTI = claims["jti"].(string)
	challenge.User = user
	challenge.idp = idp

	scopes := claims["scp"].([]interface{})
	challenge.Scopes = make([]string, len(scopes), len(scopes))
	for i, scope := range scopes {
		challenge.Scopes[i] = scope.(string)
	}

	return
}
639192
func (r *URIBuilder) ServerAddr(s string) *URIBuilder {
	r.serverAddr = s
	return r
}
950042
func (t *MockTransport) FinalAdvertiseAddr(string, int) (net.IP, int, error) {
	host, portStr, err := net.SplitHostPort(t.addr.String())
	if err != nil {
		return nil, 0, err
	}

	ip := net.ParseIP(host)
	if ip == nil {
		return nil, 0, fmt.Errorf("Failed to parse IP %q", host)
	}

	port, err := strconv.ParseInt(portStr, 10, 16)
	if err != nil {
		return nil, 0, err
	}

	return ip, int(port), nil
}
684180
func (c *Challenge) PreSolve(authz acme.Authorization) error {
	domain := challenge.GetTargetedDomain(authz)
	log.Infof("[%s] acme: Preparing to solve DNS-01", domain)

	chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
	if err != nil {
		return err
	}

	if c.provider == nil {
		return fmt.Errorf("[%s] acme: no DNS Provider configured", domain)
	}

	// Generate the Key Authorization for the challenge
	keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
	if err != nil {
		return err
	}

	err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth)
	if err != nil {
		return fmt.Errorf("[%s] acme: error presenting token: %s", domain, err)
	}

	return nil
}
641748
func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) {
	switch name {
	case "acme-dns":
		return acmedns.NewDNSProvider()
	case "alidns":
		return alidns.NewDNSProvider()
	case "azure":
		return azure.NewDNSProvider()
	case "auroradns":
		return auroradns.NewDNSProvider()
	case "bindman":
		return bindman.NewDNSProvider()
	case "bluecat":
		return bluecat.NewDNSProvider()
	case "cloudflare":
		return cloudflare.NewDNSProvider()
	case "cloudns":
		return cloudns.NewDNSProvider()
	case "cloudxns":
		return cloudxns.NewDNSProvider()
	case "conoha":
		return conoha.NewDNSProvider()
	case "designate":
		return designate.NewDNSProvider()
	case "digitalocean":
		return digitalocean.NewDNSProvider()
	case "dnsimple":
		return dnsimple.NewDNSProvider()
	case "dnsmadeeasy":
		return dnsmadeeasy.NewDNSProvider()
	case "dnspod":
		return dnspod.NewDNSProvider()
	case "dode":
		return dode.NewDNSProvider()
	case "dreamhost":
		return dreamhost.NewDNSProvider()
	case "duckdns":
		return duckdns.NewDNSProvider()
	case "dyn":
		return dyn.NewDNSProvider()
	case "fastdns":
		return fastdns.NewDNSProvider()
	case "easydns":
		return easydns.NewDNSProvider()
	case "exec":
		return exec.NewDNSProvider()
	case "exoscale":
		return exoscale.NewDNSProvider()
	case "gandi":
		return gandi.NewDNSProvider()
	case "gandiv5":
		return gandiv5.NewDNSProvider()
	case "glesys":
		return glesys.NewDNSProvider()
	case "gcloud":
		return gcloud.NewDNSProvider()
	case "godaddy":
		return godaddy.NewDNSProvider()
	case "hostingde":
		return hostingde.NewDNSProvider()
	case "httpreq":
		return httpreq.NewDNSProvider()
	case "iij":
		return iij.NewDNSProvider()
	case "inwx":
		return inwx.NewDNSProvider()
	case "joker":
		return joker.NewDNSProvider()
	case "lightsail":
		return lightsail.NewDNSProvider()
	case "linode":
		return linode.NewDNSProvider()
	case "linodev4":
		return linodev4.NewDNSProvider()
	case "manual":
		return dns01.NewDNSProviderManual()
	case "mydnsjp":
		return mydnsjp.NewDNSProvider()
	case "namecheap":
		return namecheap.NewDNSProvider()
	case "namedotcom":
		return namedotcom.NewDNSProvider()
	case "netcup":
		return netcup.NewDNSProvider()
	case "nifcloud":
		return nifcloud.NewDNSProvider()
	case "ns1":
		return ns1.NewDNSProvider()
	case "oraclecloud":
		return oraclecloud.NewDNSProvider()
	case "otc":
		return otc.NewDNSProvider()
	case "ovh":
		return ovh.NewDNSProvider()
	case "pdns":
		return pdns.NewDNSProvider()
	case "rackspace":
		return rackspace.NewDNSProvider()
	case "route53":
		return route53.NewDNSProvider()
	case "rfc2136":
		return rfc2136.NewDNSProvider()
	case "sakuracloud":
		return sakuracloud.NewDNSProvider()
	case "stackpath":
		return stackpath.NewDNSProvider()
	case "selectel":
		return selectel.NewDNSProvider()
	case "transip":
		return transip.NewDNSProvider()
	case "vegadns":
		return vegadns.NewDNSProvider()
	case "vultr":
		return vultr.NewDNSProvider()
	case "vscale":
		return vscale.NewDNSProvider()
	case "zoneee":
		return zoneee.NewDNSProvider()
	default:
		return nil, fmt.Errorf("unrecognised DNS provider: %s", name)
	}
}
59298
func (c *Client) ChallengeReady(accountKey interface{}, chal Challenge) error {
	switch chal.Type {
	case ChallengeHTTP, ChallengeTLSSNI, ChallengeDNS:
	default:
		return fmt.Errorf("unsupported challenge type '%s'", chal.Type)
	}
	auth, err := keyAuth(accountKey, chal.Token)
	if err != nil {
		return err
	}
	data := struct {
		Resource string `json:"resource"`
		KeyAuth  string `json:"keyAuthorization"`
		Type     string `json:"type"`
		Token    string `json:"token"`
	}{resourceChallenge, auth, chal.Type, chal.Token}
	sig, err := c.signObject(accountKey, &data)
	if err != nil {
		return err
	}
	resp, err := c.client.Post(chal.URI, jwsContentType, strings.NewReader(sig))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if err := checkHTTPError(resp, http.StatusAccepted); err != nil {
		return err
	}

	// Begin polling the server and check if the challenge is completed.
	pollInterval := c.PollInterval
	if pollInterval == 0 {
		pollInterval = 500 * time.Millisecond
	}
	pollTimeout := c.PollTimeout
	if pollTimeout == 0 {
		pollTimeout = 30 * time.Second
	}
	start := time.Now()
	for {
		if time.Now().Sub(start) > pollTimeout {
			if chal.Error != nil {
				return chal.Error
			}
			return errors.New("polling pending challenge timed out")
		}
		chal, err = c.Challenge(chal.URI)
		if err != nil {
			return err
		}
		switch chal.Status {
		case StatusPending, "":
			time.Sleep(pollInterval)
		case StatusInvalid:
			if chal.Error == nil {
				return errors.New("challenge returned status 'invalid' without explicit error")
			}
			// if the challenge was DNS, keep trying since the value is cached
			if chal.Type == ChallengeDNS {
				// unauthorized is the TXT value is wrong or not found
				// connection if NXDOMAIN
				if chal.Error.Typ == "urn:acme:error:unauthorized" || chal.Error.Typ == "urn:acme:error:connection" {
					time.Sleep(pollInterval)
					continue
				}
			}
			return chal.Error
		case StatusValid:
			return nil
		default:
			return fmt.Errorf("unexpected challenge status: %s", chal.Status)
		}
	}
}