当前位置: 首页>>代码示例>>Golang>>正文


Golang ocsp.ParseResponse函数代码示例

本文整理汇总了Golang中golang.org/x/crypto/ocsp.ParseResponse函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseResponse函数的具体用法?Golang ParseResponse怎么用?Golang ParseResponse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ParseResponse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NewSourceFromFile

// NewSourceFromFile reads the named file into an InMemorySource.
// The file read by this function must contain whitespace-separated OCSP
// responses. Each OCSP response must be in base64-encoded DER form (i.e.,
// PEM without headers or whitespace).  Invalid responses are ignored.
// This function pulls the entire file into an InMemorySource.
func NewSourceFromFile(responseFile string) (Source, error) {
	fileContents, err := ioutil.ReadFile(responseFile)
	if err != nil {
		return nil, err
	}

	responsesB64 := regexp.MustCompile("\\s").Split(string(fileContents), -1)
	src := InMemorySource{}
	for _, b64 := range responsesB64 {
		// if the line/space is empty just skip
		if b64 == "" {
			continue
		}
		der, tmpErr := base64.StdEncoding.DecodeString(b64)
		if tmpErr != nil {
			log.Errorf("Base64 decode error on: %s", b64)
			continue
		}

		response, tmpErr := ocsp.ParseResponse(der, nil)
		if tmpErr != nil {
			log.Errorf("OCSP decode error on: %s", b64)
			continue
		}

		src[response.SerialNumber.String()] = der
	}

	log.Infof("Read %d OCSP responses", len(src))
	return src, nil
}
开发者ID:jmhodges,项目名称:cfssl,代码行数:36,代码来源:responder.go

示例2: sendOCSPRequest

// sendOCSPRequest attempts to request an OCSP response from the
// server. The error only indicates a failure to *fetch* the
// certificate, and *does not* mean the certificate is valid.
func sendOCSPRequest(server string, req []byte, issuer *x509.Certificate) (ocspResponse *ocsp.Response, err error) {
	var resp *http.Response
	if len(req) > 256 {
		buf := bytes.NewBuffer(req)
		resp, err = http.Post(server, "application/ocsp-request", buf)
	} else {
		reqURL := server + "/" + base64.StdEncoding.EncodeToString(req)
		resp, err = http.Get(reqURL)
	}

	if err != nil {
		return
	}

	if resp.StatusCode != http.StatusOK {
		return
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	resp.Body.Close()

	if bytes.Equal(body, ocspUnauthorised) {
		return
	}

	if bytes.Equal(body, ocspMalformed) {
		return
	}

	return ocsp.ParseResponse(body, issuer)
}
开发者ID:jamesbjackson,项目名称:cfssl,代码行数:37,代码来源:revoke.go

示例3: OCSP

func (cp *TLSConf) OCSP() (err error) {
	if cp.IsEnabled() && len(cp.kp.Certificate) > 1 {
		for _, ocsp_server := range cp.cert.OCSPServer {
			for _, issuing := range cp.cert.IssuingCertificateURL {
				//log.Println("OCSP : ["+ocsp_server+"] ["+issuing+"]")
				issuer, err := load_issuer(issuing)
				if err != nil {
					return err
				}

				request, err := ocsp.CreateRequest(cp.cert, issuer, &ocsp.RequestOptions{crypto.SHA1})
				if err != nil {
					return err
				}

				staple := get_or_post_OCSP(ocsp_server, "application/ocsp-request", request)
				if len(staple) < MIN_STAPLE_SIZE {
					return nil
				}

				_, err = ocsp.ParseResponse(staple, issuer)
				//log.Printf("\n%+v\n", struct{
				//		ProducedAt, ThisUpdate, NextUpdate string
				//	}{ resp.ProducedAt.Format(time.RFC3339), resp.ThisUpdate.Format(time.RFC3339), resp.NextUpdate.Format(time.RFC3339) } )
				if err == nil {
					cp.kp.OCSPStaple = staple
					return nil
				}
			}
		}
	}
	return err
}
开发者ID:Zigazou,项目名称:nataraja,代码行数:33,代码来源:CertPair.go

示例4: DeleteOldStapleFiles

// DeleteOldStapleFiles deletes cached OCSP staples that have expired.
// TODO: Should we do this for certificates too?
func DeleteOldStapleFiles() {
	files, err := ioutil.ReadDir(ocspFolder)
	if err != nil {
		// maybe just hasn't been created yet; no big deal
		return
	}
	for _, file := range files {
		if file.IsDir() {
			// wierd, what's a folder doing inside the OCSP cache?
			continue
		}
		stapleFile := filepath.Join(ocspFolder, file.Name())
		ocspBytes, err := ioutil.ReadFile(stapleFile)
		if err != nil {
			continue
		}
		resp, err := ocsp.ParseResponse(ocspBytes, nil)
		if err != nil {
			// contents are invalid; delete it
			err = os.Remove(stapleFile)
			if err != nil {
				log.Printf("[ERROR] Purging corrupt staple file %s: %v", stapleFile, err)
			}
		}
		if time.Now().After(resp.NextUpdate) {
			// response has expired; delete it
			err = os.Remove(stapleFile)
			if err != nil {
				log.Printf("[ERROR] Purging expired staple file %s: %v", stapleFile, err)
			}
		}
	}
}
开发者ID:FiloSottile,项目名称:caddy,代码行数:35,代码来源:maintain.go

示例5: main

func main() {
	issuerFile := flag.String("issuer", "", "Issuer certificate (PEM)")
	responderFile := flag.String("responder", "", "OCSP responder certificate (DER)")
	targetFile := flag.String("target", "", "Certificate whose status is being reported (PEM)")
	pkcs11File := flag.String("pkcs11", "", pkcs11Usage)
	outFile := flag.String("out", "", "File to which the OCSP response will be written")
	thisUpdateString := flag.String("thisUpdate", "", "Time for ThisUpdate field, RFC3339 format (e.g. 2016-09-02T00:00:00Z)")
	nextUpdateString := flag.String("nextUpdate", "", "Time for NextUpdate field, RFC3339 format")
	status := flag.Int("status", 0, "Status for response (0 = good, 1 = revoked)")
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, usage)
		flag.PrintDefaults()
	}
	flag.Parse()

	if len(*outFile) == 0 {
		cmd.FailOnError(fmt.Errorf("No output file provided"), "")
	}
	thisUpdate, err := time.Parse(time.RFC3339, *thisUpdateString)
	cmd.FailOnError(err, "Parsing thisUpdate flag")
	nextUpdate, err := time.Parse(time.RFC3339, *nextUpdateString)
	cmd.FailOnError(err, "Parsing nextUpdate flag")

	issuer, responder, target, pkcs11, err := readFiles(*issuerFile, *responderFile, *targetFile, *pkcs11File)
	cmd.FailOnError(err, "Failed to read files")

	// Instantiate the private key from PKCS11
	priv, err := pkcs11key.New(pkcs11.Module, pkcs11.TokenLabel, pkcs11.PIN, pkcs11.PrivateKeyLabel)
	cmd.FailOnError(err, "Failed to load PKCS#11 key")

	// Populate the remaining fields in the template
	template := ocsp.Response{
		SerialNumber: target.SerialNumber,
		Certificate:  responder,
		Status:       *status,
		ThisUpdate:   thisUpdate,
		NextUpdate:   nextUpdate,
	}

	if !core.KeyDigestEquals(responder.PublicKey, priv.Public()) {
		cmd.FailOnError(fmt.Errorf("PKCS#11 pubkey does not match pubkey "+
			"in responder certificate"), "loading keys")
	}

	// Sign the OCSP response
	responseBytes, err := ocsp.CreateResponse(issuer, responder, template, priv)
	cmd.FailOnError(err, "Failed to sign OCSP response")

	_, err = ocsp.ParseResponse(responseBytes, nil)
	cmd.FailOnError(err, "Failed to parse signed response")

	responseBytesBase64 := base64.StdEncoding.EncodeToString(responseBytes) + "\n"

	// Write the OCSP response to stdout
	err = ioutil.WriteFile(*outFile, []byte(responseBytesBase64), 0666)
	cmd.FailOnError(err, "Failed to write output file")
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:57,代码来源:main.go

示例6: GetOCSPForCert

// GetOCSPForCert takes a PEM encoded cert or cert bundle and returns a OCSP
// response from the OCSP endpoint in the certificate.
// This []byte can be passed directly  into the OCSPStaple property of a tls.Certificate.
// If the bundle only contains the issued certificate, this function will try
// to get the issuer certificate from the IssuingCertificateURL in the certificate.
func GetOCSPForCert(bundle []byte) ([]byte, error) {
	certificates, err := parsePEMBundle(bundle)
	if err != nil {
		return nil, err
	}

	// We only got one certificate, means we have no issuer certificate - get it.
	if len(certificates) == 1 {
		// TODO: build fallback. If this fails, check the remaining array entries.
		resp, err := http.Get(certificates[0].IssuingCertificateURL[0])
		if err != nil {
			return nil, err
		}

		issuerBytes, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, err
		}

		issuerCert, err := x509.ParseCertificate(issuerBytes)
		if err != nil {
			return nil, err
		}

		// Insert it into the slice on position 0
		// We want it ordered right SRV CRT -> CA
		certificates = append(certificates, issuerCert)
	}

	// We expect the certificate slice to be ordered downwards the chain.
	// SRV CRT -> CA. We need to pull the cert and issuer cert out of it,
	// which should always be the last two certificates.
	issuedCert := certificates[0]
	issuerCert := certificates[1]

	// Finally kick off the OCSP request.
	ocspReq, err := ocsp.CreateRequest(issuedCert, issuerCert, nil)
	if err != nil {
		return nil, err
	}

	reader := bytes.NewReader(ocspReq)
	req, err := http.Post(issuedCert.OCSPServer[0], "application/ocsp-request", reader)
	if err != nil {
		return nil, err
	}

	ocspResBytes, err := ioutil.ReadAll(req.Body)
	_, err = ocsp.ParseResponse(ocspResBytes, nil)
	if err != nil {
		log.Printf("OCSPParse Error: %v", err)
		return nil, err
	}

	return ocspResBytes, nil
}
开发者ID:drewwells,项目名称:lego,代码行数:61,代码来源:crypto.go

示例7: init

func init() {
	bytes, err := hex.DecodeString(OCSPResponseHex)
	if err != nil {
		panic(err)
	}
	OCSPResponseBytes = bytes
	OCSPResponse, err = ocsp.ParseResponse(bytes, nil)
	if err != nil {
		panic(err)
	}
}
开发者ID:vnadgir-ef,项目名称:vulcand,代码行数:11,代码来源:testutils.go

示例8: Verify

func (tcc *TLSClientConfig) Verify(conn *tls.Conn) (*TLSState, error) {
	var ocsprep *ocsp.Response
	var der []byte
	var err error

	res := new(TLSState)
	cstate := conn.ConnectionState()

	res.SNIExist = (tcc.SNI != "")
	res.PKPExist = (tcc.PKPs != nil && len(tcc.PKPs) > 0)

	if cstate.OCSPResponse != nil {
		ocsprep, err = ocsp.ParseResponse(cstate.OCSPResponse, nil)
		if err != nil {
			return nil, err
		}
		res.OCSPExist = true
		res.OCSPValid = (ocsprep.Status == ocsp.Good)
		res.OCSPUnknown = (ocsprep.Status == ocsp.Unknown)
	}

	for _, peercert := range cstate.PeerCertificates {
		der, err = x509.MarshalPKIXPublicKey(peercert.PublicKey)
		if err != nil {
			return nil, err
		}

		if res.SNIExist && !res.SNIValid && peercert.VerifyHostname(tcc.SNI) == nil {
			res.SNIValid = true
		}

		if res.OCSPValid && !res.OCSPChecked && ocsprep.CheckSignatureFrom(peercert) == nil {
			res.OCSPChecked = true
		}

		rawhash := sha256.Sum256(der)
		hash := base64.StdEncoding.EncodeToString(rawhash[:])

		if res.PKPExist {
			res.PKPCerts++
			valid, ok := tcc.PKPs[hash]
			switch {
			case ok && valid:
				res.PKPValid++
			case ok && !valid:
				res.PKPInvalid++
			}
		}
	}

	return res, nil
}
开发者ID:nathanaelle,项目名称:pasnet,代码行数:52,代码来源:tls.go

示例9: CheckOCSP

// Checks OCSP for a certificate. The immediate issuer must be specified. If
// the HTTP client is nil, the default client is used. If the certificate does
// not support OCSP, (nil, nil) is returned.  Uses HTTP GET rather than POST.
// The response is verified. The caller must check the response status.
func CheckOCSP(httpClient *http.Client, crt, issuer *x509.Certificate) (*ocsp.Response, error) {
	if httpClient == nil {
		httpClient = http.DefaultClient
	}

	if len(crt.OCSPServer) == 0 {
		return nil, nil
	}

	b, err := ocsp.CreateRequest(crt, issuer, nil)
	if err != nil {
		return nil, err
	}

	b64 := base64.StdEncoding.EncodeToString(b)
	path := crt.OCSPServer[0] + "/" + b64

	req, err := http.NewRequest("GET", path, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Accept", "application/ocsp-response")

	res, err := httpClient.Do(req)
	if err != nil {
		return nil, err
	}

	defer res.Body.Close()

	if res.StatusCode != 200 {
		return nil, fmt.Errorf("OCSP response has status %#v", res.Status)
	}

	if res.Header.Get("Content-Type") != "application/ocsp-response" {
		return nil, fmt.Errorf("response to OCSP request had unexpected content type")
	}

	resb, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	return ocsp.ParseResponse(resb, issuer)
}
开发者ID:meyskens,项目名称:acme,代码行数:50,代码来源:ocsp.go

示例10: CheckOCSPRaw

// Checks OCSP for a certificate. The immediate issuer must be specified. If
// the certificate does not support OCSP, (nil, nil) is returned.  Uses HTTP
// GET rather than POST. The response is verified. The caller must check the
// response status. The raw OCSP response is also returned, even if parsing
// failed and err is non-nil.
func (c *Client) CheckOCSPRaw(crt, issuer *x509.Certificate, ctx context.Context) (parsedResponse *ocsp.Response, rawResponse []byte, err error) {
	if len(crt.OCSPServer) == 0 {
		return
	}

	b, err := ocsp.CreateRequest(crt, issuer, nil)
	if err != nil {
		return
	}

	b64 := base64.StdEncoding.EncodeToString(b)
	path := crt.OCSPServer[0] + "/" + b64

	req, err := http.NewRequest("GET", path, nil)
	if err != nil {
		return
	}

	req.Header.Set("Accept", "application/ocsp-response")

	res, err := c.doReqActual(req, ctx)
	if err != nil {
		return
	}

	defer res.Body.Close()

	if res.StatusCode != 200 {
		err = fmt.Errorf("OCSP response has status %#v", res.Status)
		return
	}

	if res.Header.Get("Content-Type") != "application/ocsp-response" {
		err = fmt.Errorf("response to OCSP request had unexpected content type")
		return
	}

	// Read response, limiting response to 1MiB.
	rawResponse, err = ioutil.ReadAll(denet.LimitReader(res.Body, 1*1024*1024))
	if err != nil {
		return
	}

	parsedResponse, err = ocsp.ParseResponse(rawResponse, issuer)
	return
}
开发者ID:hlandau,项目名称:acme,代码行数:51,代码来源:ocsp.go

示例11: TestSignNoResponder

func TestSignNoResponder(t *testing.T) {
	req, dur := setup(t)
	s, err := NewSignerFromFile(serverCertFile, serverCertFile, serverKeyFile, dur)
	if err != nil {
		t.Fatalf("Signer creation failed: %v", err)
	}
	respBytes, err := s.Sign(req)
	if err != nil {
		t.Fatal("Failed to sign with no responder cert")
	}

	resp, err := ocsp.ParseResponse(respBytes, nil)
	if err != nil {
		t.Fatal("Failed to fail on improper status code")
	}
	if resp.Certificate != nil {
		t.Fatal("Response contain responder cert even though it was identical to issuer")
	}
}
开发者ID:jamesbjackson,项目名称:cfssl,代码行数:19,代码来源:ocsp_test.go

示例12: main

func main() {
	for _, host := range os.Args[1:] {
		fmt.Println(host)
		host := net.JoinHostPort(host, "443")
		conn, err := tls.Dial("tcp", host, nil)
		peerCerts := conn.ConnectionState().PeerCertificates
		resp, err := getResponse(peerCerts[0], peerCerts[1])
		if err != nil {
			log.Println(err)
			continue
		}
		ocspResp, err := ocsp.ParseResponse(resp, peerCerts[1])
		if err != nil {
			log.Println(err)
			continue
		}
		fmt.Println("ProducedAt:", ocspResp.ProducedAt)
		fmt.Println("NextUpdate:", ocspResp.NextUpdate)
		fmt.Println("Delta:", ocspResp.NextUpdate.Sub(ocspResp.ProducedAt))
	}
}
开发者ID:jacobhaven,项目名称:goutils,代码行数:21,代码来源:ocsp-staple.go

示例13: sendOCSPRequest

// sendOCSPRequest attempts to request an OCSP response from the
// server. The error only indicates a failure to *fetch* the
// certificate, and *does not* mean the certificate is valid.
func sendOCSPRequest(server string, req []byte, issuer *x509.Certificate) (*ocsp.Response, error) {
	var resp *http.Response
	var err error
	if len(req) > 256 {
		buf := bytes.NewBuffer(req)
		resp, err = http.Post(server, "application/ocsp-request", buf)
	} else {
		reqURL := server + "/" + base64.StdEncoding.EncodeToString(req)
		resp, err = http.Get(reqURL)
	}

	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("failed to retrieve OSCP")
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	resp.Body.Close()

	switch {
	case bytes.Equal(body, ocsp.UnauthorizedErrorResponse):
		return nil, errors.New("OSCP unauthorized")
	case bytes.Equal(body, ocsp.MalformedRequestErrorResponse):
		return nil, errors.New("OSCP malformed")
	case bytes.Equal(body, ocsp.InternalErrorErrorResponse):
		return nil, errors.New("OSCP internal error")
	case bytes.Equal(body, ocsp.TryLaterErrorResponse):
		return nil, errors.New("OSCP try later")
	case bytes.Equal(body, ocsp.SigRequredErrorResponse):
		return nil, errors.New("OSCP signature required")
	}

	return ocsp.ParseResponse(body, issuer)
}
开发者ID:constabulary,项目名称:docker-depfile-example,代码行数:43,代码来源:revoke.go

示例14: Read

// Read reads a OCSP response from disk
func (dc *DiskCache) Read(name string, serial *big.Int, issuer *x509.Certificate) (*ocsp.Response, []byte) {
	name = path.Join(dc.path, name) + ".resp"
	response, err := ioutil.ReadFile(name)
	if err != nil && !os.IsNotExist(err) {
		dc.failer.Fail(dc.logger, fmt.Sprintf("[disk-cache] Failed to read response from '%s': %s", name, err))
		return nil, nil
	} else if err != nil {
		return nil, nil // no file exists yet
	}
	parsed, err := ocsp.ParseResponse(response, issuer)
	if err != nil {
		dc.failer.Fail(dc.logger, fmt.Sprintf("[disk-cache] Failed to parse response from '%s': %s", name, err))
		return nil, nil
	}
	err = stapledOCSP.VerifyResponse(dc.clk.Now(), serial, parsed)
	if err != nil {
		dc.failer.Fail(dc.logger, fmt.Sprintf("[disk-cache] Failed to verify response from '%s': %s", name, err))
		return nil, nil
	}
	dc.logger.Info("[disk-cache] Loaded valid response from '%s'", name)
	return parsed, response
}
开发者ID:rolandshoemaker,项目名称:stapled,代码行数:23,代码来源:stable.go

示例15: GetOCSPInfo

// GetOCSPInfo is used to get OCSP response details from []byte containing the response. The
// OCSP bytes input needs to be a DER encoded OCSP response. An OCSPInfo struct is returned
// unless an error is encountered and then a non-nil error is returned.
func GetOCSPInfo(ocspBytes []byte) (OCSPInfo, error) {
	// TODO: Add issuer so the signature is validated
	ocspInfo := new(OCSPInfo)
	ocspResp, err := ocsp.ParseResponse(ocspBytes, nil)
	if err != nil {
		return *ocspInfo, err
	}

	ocspInfo.Serial = ocspResp.SerialNumber
	ocspInfo.ThisUpdate = ocspResp.ThisUpdate
	ocspInfo.NextUpdate = ocspResp.NextUpdate
	switch ocspResp.Status {
	case ocsp.Good:
		ocspInfo.Status = "Good"
	case ocsp.Revoked:
		ocspInfo.Status = "Revoked"
	case ocsp.Unknown:
		ocspInfo.Status = "Unknown"
	}

	return *ocspInfo, err
}
开发者ID:spazbite187,项目名称:snatchtls,代码行数:25,代码来源:keystone.go


注:本文中的golang.org/x/crypto/ocsp.ParseResponse函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。