forked from TrueCloudLab/lego
Compare commits
No commits in common. "gh-pages" and "tcl/master" have entirely different histories.
gh-pages
...
tcl/master
1362 changed files with 121569 additions and 743539 deletions
8
.dockerignore
Normal file
8
.dockerignore
Normal file
|
@ -0,0 +1,8 @@
|
|||
lego.exe
|
||||
.lego
|
||||
.gitcookies
|
||||
.idea
|
||||
.vscode/
|
||||
dist/
|
||||
builds/
|
||||
docs/
|
BIN
.gitcookies.enc
Normal file
BIN
.gitcookies.enc
Normal file
Binary file not shown.
1
.github/FUNDING.yml
vendored
Normal file
1
.github/FUNDING.yml
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
github: ldez
|
104
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
104
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
|
@ -0,0 +1,104 @@
|
|||
name: Bug Report
|
||||
description: Create a report to help us improve.
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Welcome
|
||||
options:
|
||||
- label: Yes, I'm using a binary release within 2 latest releases.
|
||||
required: true
|
||||
- label: Yes, I've searched similar issues on GitHub and didn't find any.
|
||||
required: true
|
||||
- label: Yes, I've included all information below (version, config, etc).
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: What did you expect to see?
|
||||
placeholder: Description.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: current
|
||||
attributes:
|
||||
label: What did you see instead?
|
||||
placeholder: Description.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: type
|
||||
attributes:
|
||||
label: How do you use lego?
|
||||
options:
|
||||
- Library
|
||||
- Binary
|
||||
- Docker image
|
||||
- Through Traefik
|
||||
- Through Caddy
|
||||
- Through Terraform ACME provider
|
||||
- Through Bitnami
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Reproduction steps
|
||||
description: "How do you trigger this bug? Please walk us through it step by step."
|
||||
placeholder: |
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: version
|
||||
attributes:
|
||||
label: Version of lego
|
||||
description: |-
|
||||
```console
|
||||
$ lego --version
|
||||
```
|
||||
placeholder: Paste output here
|
||||
render: console
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Logs
|
||||
value: |-
|
||||
<details>
|
||||
|
||||
```console
|
||||
# paste output here
|
||||
```
|
||||
|
||||
</details>
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: go-env
|
||||
attributes:
|
||||
label: Go environment (if applicable)
|
||||
value: |-
|
||||
<details>
|
||||
|
||||
```console
|
||||
$ go version && go env
|
||||
# paste output here
|
||||
```
|
||||
|
||||
</details>
|
||||
validations:
|
||||
required: false
|
8
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
8
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Questions
|
||||
url: https://github.com/go-acme/lego/discussions
|
||||
about: If you have a question, or are looking for advice, please post on our Discussions section!
|
||||
- name: lego documentation
|
||||
url: https://go-acme.github.io/lego/
|
||||
about: Please take a look to our documentation.
|
34
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
34
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
|
@ -0,0 +1,34 @@
|
|||
name: Feature request
|
||||
description: Suggest an idea for this project.
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Welcome
|
||||
options:
|
||||
- label: Yes, I've searched similar issues on GitHub and didn't find any.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: type
|
||||
attributes:
|
||||
label: How do you use lego?
|
||||
options:
|
||||
- Library
|
||||
- Binary
|
||||
- Docker image
|
||||
- Through Traefik
|
||||
- Through Caddy
|
||||
- Through Terraform ACME provider
|
||||
- Through Bitnami
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Detailed Description
|
||||
placeholder: Description.
|
||||
validations:
|
||||
required: true
|
60
.github/ISSUE_TEMPLATE/new_dns_provider.yml
vendored
Normal file
60
.github/ISSUE_TEMPLATE/new_dns_provider.yml
vendored
Normal file
|
@ -0,0 +1,60 @@
|
|||
name: New DNS provider support
|
||||
description: Request for the support of a new DNS provider.
|
||||
title: "Support for provider: <put the name of your provider>"
|
||||
labels: [enhancement, new-provider]
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Welcome
|
||||
options:
|
||||
- label: Yes, I've searched similar issues on GitHub and didn't find any.
|
||||
required: true
|
||||
- label: Yes, the DNS provider exposes a public API.
|
||||
required: true
|
||||
- label: Yes, I know that the lego maintainers don't have an account in all DNS providers in the world.
|
||||
required: true
|
||||
- label: Yes, I'm able to create a pull request and be able to maintain the implementation.
|
||||
required: false
|
||||
- label: Yes, I'm able to test an implementation if someone creates a pull request to add the support of this DNS provider.
|
||||
required: false
|
||||
|
||||
- type: dropdown
|
||||
id: type
|
||||
attributes:
|
||||
label: How do you use lego?
|
||||
options:
|
||||
- Library
|
||||
- Binary
|
||||
- Docker image
|
||||
- Through Traefik
|
||||
- Through Caddy
|
||||
- Through Terraform ACME provider
|
||||
- Through Bitnami
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: provider-link
|
||||
attributes:
|
||||
label: Link to the DNS provider
|
||||
placeholder: Put your link here.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: api-link
|
||||
attributes:
|
||||
label: Link to the API documentation
|
||||
placeholder: Put your link here.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Additional Notes
|
||||
placeholder: Your notes.
|
||||
validations:
|
||||
required: false
|
50
.github/workflows/documentation.yml
vendored
Normal file
50
.github/workflows/documentation.yml
vendored
Normal file
|
@ -0,0 +1,50 @@
|
|||
name: Documentation
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
|
||||
doc:
|
||||
name: Build and deploy documentation
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GO_VERSION: '1.20'
|
||||
HUGO_VERSION: 0.101.0
|
||||
CGO_ENABLED: 0
|
||||
|
||||
steps:
|
||||
|
||||
# https://github.com/marketplace/actions/setup-go-environment
|
||||
- name: Set up Go ${{ env.GO_VERSION }}
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
# https://github.com/marketplace/actions/checkout
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Generate DNS docs
|
||||
run: make generate-dns
|
||||
|
||||
- name: Install Hugo
|
||||
run: |
|
||||
wget -O /tmp/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_${HUGO_VERSION}_Linux-64bit.deb
|
||||
sudo dpkg -i /tmp/hugo.deb
|
||||
|
||||
- name: Build Documentation
|
||||
run: make docs-build
|
||||
|
||||
# https://github.com/marketplace/actions/github-pages
|
||||
- name: Deploy to GitHub Pages
|
||||
uses: crazy-max/ghaction-github-pages@v3
|
||||
with:
|
||||
target_branch: gh-pages
|
||||
build_dir: docs/public
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
55
.github/workflows/go-cross.yml
vendored
Normal file
55
.github/workflows/go-cross.yml
vendored
Normal file
|
@ -0,0 +1,55 @@
|
|||
name: Go Matrix
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
|
||||
cross:
|
||||
name: Go
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
CGO_ENABLED: 0
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [ '1.19', '1.20', 1.x ]
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
|
||||
steps:
|
||||
# https://github.com/marketplace/actions/setup-go-environment
|
||||
- name: Set up Go ${{ matrix.go-version }}
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
|
||||
# https://github.com/marketplace/actions/checkout
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# https://github.com/marketplace/actions/cache
|
||||
- name: Cache Go modules
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
# In order:
|
||||
# * Module download cache
|
||||
# * Build cache (Linux)
|
||||
# * Build cache (Mac)
|
||||
# * Build cache (Windows)
|
||||
path: |
|
||||
~/go/pkg/mod
|
||||
~/.cache/go-build
|
||||
~/Library/Caches/go-build
|
||||
%LocalAppData%\go-build
|
||||
key: ${{ runner.os }}-${{ matrix.go-version }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ matrix.go-version }}-go-
|
||||
|
||||
- name: Test
|
||||
run: go test -v -cover ./...
|
||||
|
||||
- name: Build
|
||||
run: go build -v -ldflags "-s -w" -trimpath -o ./dist/lego ./cmd/lego/
|
85
.github/workflows/pr.yml
vendored
Normal file
85
.github/workflows/pr.yml
vendored
Normal file
|
@ -0,0 +1,85 @@
|
|||
name: Main
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
|
||||
main:
|
||||
name: Main Process
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GO_VERSION: '1.20'
|
||||
GOLANGCI_LINT_VERSION: v1.53.1
|
||||
HUGO_VERSION: 0.54.0
|
||||
CGO_ENABLED: 0
|
||||
LEGO_E2E_TESTS: CI
|
||||
MEMCACHED_HOSTS: localhost:11211
|
||||
|
||||
steps:
|
||||
|
||||
# https://github.com/marketplace/actions/setup-go-environment
|
||||
- name: Set up Go ${{ env.GO_VERSION }}
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
# https://github.com/marketplace/actions/checkout
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# https://github.com/marketplace/actions/cache
|
||||
- name: Cache Go modules
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
- name: Check and get dependencies
|
||||
run: |
|
||||
go mod tidy
|
||||
git diff --exit-code go.mod
|
||||
git diff --exit-code go.sum
|
||||
|
||||
# https://golangci-lint.run/usage/install#other-ci
|
||||
- name: Install golangci-lint ${{ env.GOLANGCI_LINT_VERSION }}
|
||||
run: |
|
||||
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION}
|
||||
golangci-lint --version
|
||||
|
||||
- name: Install Pebble
|
||||
run: go install github.com/letsencrypt/pebble/v2/cmd/pebble@main
|
||||
|
||||
- name: Install challtestsrv
|
||||
run: go install github.com/letsencrypt/pebble/v2/cmd/pebble-challtestsrv@main
|
||||
|
||||
- name: Set up a Memcached server
|
||||
uses: niden/actions-memcached@v7
|
||||
|
||||
- name: Setup /etc/hosts
|
||||
run: |
|
||||
echo "127.0.0.1 acme.wtf" | sudo tee -a /etc/hosts
|
||||
echo "127.0.0.1 lego.wtf" | sudo tee -a /etc/hosts
|
||||
echo "127.0.0.1 acme.lego.wtf" | sudo tee -a /etc/hosts
|
||||
echo "127.0.0.1 légô.wtf" | sudo tee -a /etc/hosts
|
||||
echo "127.0.0.1 xn--lg-bja9b.wtf" | sudo tee -a /etc/hosts
|
||||
|
||||
- name: Make
|
||||
run: |
|
||||
make
|
||||
make clean
|
||||
|
||||
- name: Install Hugo
|
||||
run: |
|
||||
wget -O /tmp/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_${HUGO_VERSION}_Linux-64bit.deb
|
||||
sudo dpkg -i /tmp/hugo.deb
|
||||
|
||||
- name: Build Documentation
|
||||
run: make docs-build
|
63
.github/workflows/release.yml
vendored
Normal file
63
.github/workflows/release.yml
vendored
Normal file
|
@ -0,0 +1,63 @@
|
|||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
|
||||
jobs:
|
||||
|
||||
release:
|
||||
name: Release version
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GO_VERSION: '1.20'
|
||||
CGO_ENABLED: 0
|
||||
|
||||
steps:
|
||||
|
||||
# https://github.com/marketplace/actions/free-disk-space-ubuntu
|
||||
- name: Free Disk Space
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
with:
|
||||
# this might remove tools that are actually needed
|
||||
tool-cache: false
|
||||
|
||||
# all of these default to true
|
||||
android: true
|
||||
dotnet: true
|
||||
haskell: true
|
||||
large-packages: true
|
||||
docker-images: true
|
||||
swap-storage: false
|
||||
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go ${{ env.GO_VERSION }}
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
|
||||
- name: Docker Login
|
||||
env:
|
||||
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
|
||||
run: echo "${DOCKER_PASSWORD}" | docker login --username "${DOCKER_USERNAME}" --password-stdin
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
# https://goreleaser.com/ci/actions/
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
version: latest
|
||||
args: release -p 1 --clean --timeout=90m
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GH_TOKEN_REPO }}
|
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
.lego
|
||||
.gitcookies
|
||||
.idea
|
||||
.vscode/
|
||||
dist/
|
||||
builds/
|
225
.golangci.yml
Normal file
225
.golangci.yml
Normal file
|
@ -0,0 +1,225 @@
|
|||
run:
|
||||
timeout: 10m
|
||||
skip-files: []
|
||||
|
||||
linters-settings:
|
||||
govet:
|
||||
check-shadowing: true
|
||||
gocyclo:
|
||||
min-complexity: 12
|
||||
maligned:
|
||||
suggest-new: true
|
||||
goconst:
|
||||
min-len: 3
|
||||
min-occurrences: 3
|
||||
funlen:
|
||||
lines: -1
|
||||
statements: 50
|
||||
misspell:
|
||||
locale: US
|
||||
ignore-words:
|
||||
- internetbs
|
||||
depguard:
|
||||
rules:
|
||||
main:
|
||||
deny:
|
||||
- pkg: "github.com/instana/testify"
|
||||
desc: not allowed
|
||||
- pkg: "github.com/pkg/errors"
|
||||
desc: Should be replaced by standard lib errors package
|
||||
tagalign:
|
||||
align: false
|
||||
order:
|
||||
- xml
|
||||
- json
|
||||
- yaml
|
||||
- yml
|
||||
- toml
|
||||
- mapstructure
|
||||
- url
|
||||
godox:
|
||||
keywords:
|
||||
- FIXME
|
||||
gocritic:
|
||||
enabled-tags:
|
||||
- diagnostic
|
||||
- style
|
||||
- performance
|
||||
disabled-checks:
|
||||
- paramTypeCombine # already handle by gofumpt.extra-rules
|
||||
- whyNoLint # already handle by nonolint
|
||||
- unnamedResult
|
||||
- hugeParam
|
||||
- sloppyReassign
|
||||
- rangeValCopy
|
||||
- octalLiteral
|
||||
- ptrToRefParam
|
||||
- appendAssign
|
||||
- ruleguard
|
||||
- httpNoBody
|
||||
- exposedSyncMutex
|
||||
revive:
|
||||
rules:
|
||||
- name: struct-tag
|
||||
- name: blank-imports
|
||||
- name: context-as-argument
|
||||
- name: context-keys-type
|
||||
- name: dot-imports
|
||||
- name: error-return
|
||||
- name: error-strings
|
||||
- name: error-naming
|
||||
- name: exported
|
||||
disabled: true
|
||||
- name: if-return
|
||||
- name: increment-decrement
|
||||
- name: var-naming
|
||||
- name: var-declaration
|
||||
- name: package-comments
|
||||
disabled: true
|
||||
- name: range
|
||||
- name: receiver-naming
|
||||
- name: time-naming
|
||||
- name: unexported-return
|
||||
- name: indent-error-flow
|
||||
- name: errorf
|
||||
- name: empty-block
|
||||
- name: superfluous-else
|
||||
- name: unused-parameter
|
||||
disabled: true
|
||||
- name: unreachable-code
|
||||
- name: redefines-builtin-id
|
||||
|
||||
linters:
|
||||
enable-all: true
|
||||
disable:
|
||||
- deadcode # deprecated
|
||||
- exhaustivestruct # deprecated
|
||||
- golint # deprecated
|
||||
- ifshort # deprecated
|
||||
- interfacer # deprecated
|
||||
- maligned # deprecated
|
||||
- nosnakecase # deprecated
|
||||
- scopelint # deprecated
|
||||
- structcheck # deprecated
|
||||
- varcheck # deprecated
|
||||
- cyclop # duplicate of gocyclo
|
||||
- sqlclosecheck # not relevant (SQL)
|
||||
- rowserrcheck # not relevant (SQL)
|
||||
- execinquery # not relevant (SQL)
|
||||
- lll
|
||||
- gosec
|
||||
- dupl # not relevant
|
||||
- prealloc # too many false-positive
|
||||
- bodyclose # too many false-positive
|
||||
- gomnd
|
||||
- testpackage # not relevant
|
||||
- tparallel # not relevant
|
||||
- paralleltest # not relevant
|
||||
- nestif # too many false-positive
|
||||
- wrapcheck
|
||||
- goerr113 # not relevant
|
||||
- nlreturn # not relevant
|
||||
- wsl # not relevant
|
||||
- exhaustive # not relevant
|
||||
- exhaustruct # not relevant
|
||||
- makezero # not relevant
|
||||
- forbidigo
|
||||
- varnamelen # not relevant
|
||||
- nilnil # not relevant
|
||||
- ireturn # not relevant
|
||||
- contextcheck # too many false-positive
|
||||
- tenv # we already have a test "framework" to handle env vars
|
||||
- noctx
|
||||
- forcetypeassert
|
||||
- tagliatelle
|
||||
- errname
|
||||
- errchkjson
|
||||
- nonamedreturns
|
||||
- musttag # false-positive https://github.com/junk1tm/musttag/issues/17
|
||||
- gosmopolitan # not relevant
|
||||
|
||||
issues:
|
||||
exclude-use-default: false
|
||||
max-per-linter: 0
|
||||
max-same-issues: 0
|
||||
exclude:
|
||||
- 'Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*printf?|os\.(Un)?Setenv). is not checked'
|
||||
- 'exported (type|method|function) (.+) should have comment or be unexported'
|
||||
- 'ST1000: at least one file in a package should have a package comment'
|
||||
exclude-rules:
|
||||
- path: (.+)_test.go
|
||||
linters:
|
||||
- funlen
|
||||
- goconst
|
||||
- maintidx
|
||||
- path: providers/dns/dns_providers.go
|
||||
linters:
|
||||
- gocyclo
|
||||
- path: providers/dns/gcloud/googlecloud_test.go
|
||||
text: 'string `(lego\.wtf|manhattan)` has (\d+) occurrences, make it a constant'
|
||||
- path: providers/dns/zoneee/zoneee_test.go
|
||||
text: 'string `(bar|foo)` has (\d+) occurrences, make it a constant'
|
||||
- path: certcrypto/crypto.go
|
||||
text: '(tlsFeatureExtensionOID|ocspMustStapleFeature) is a global variable'
|
||||
- path: challenge/dns01/nameserver.go
|
||||
text: '(defaultNameservers|recursiveNameservers|fqdnSoaCache|muFqdnSoaCache) is a global variable'
|
||||
- path: challenge/dns01/nameserver_.+.go
|
||||
text: 'dnsTimeout is a global variable'
|
||||
- path: challenge/dns01/nameserver_test.go
|
||||
text: 'findXByFqdnTestCases is a global variable'
|
||||
- path: challenge/http01/domain_matcher.go
|
||||
text: 'string `Host` has \d occurrences, make it a constant'
|
||||
- path: challenge/http01/domain_matcher.go
|
||||
text: 'cyclomatic complexity \d+ of func `parseForwardedHeader` is high'
|
||||
- path: challenge/http01/domain_matcher.go
|
||||
text: "Function 'parseForwardedHeader' has too many statements"
|
||||
- path: challenge/tlsalpn01/tls_alpn_challenge.go
|
||||
text: 'idPeAcmeIdentifierV1 is a global variable'
|
||||
- path: log/logger.go
|
||||
text: 'Logger is a global variable'
|
||||
- path: 'e2e/(dnschallenge/)?[\d\w]+_test.go'
|
||||
text: load is a global variable
|
||||
- path: 'providers/dns/([\d\w]+/)*[\d\w]+_test.go'
|
||||
text: 'envTest is a global variable'
|
||||
- path: providers/dns/namecheap/namecheap_test.go
|
||||
text: 'testCases is a global variable'
|
||||
- path: providers/dns/acmedns/acmedns_test.go
|
||||
text: 'egTestAccount is a global variable'
|
||||
- path: providers/http/memcached/memcached_test.go
|
||||
text: 'memcachedHosts is a global variable'
|
||||
- path: providers/dns/sakuracloud/client_test.go
|
||||
text: 'cyclomatic complexity 13 of func `(TestDNSProvider_cleanupTXTRecord_concurrent|TestDNSProvider_addTXTRecord_concurrent)` is high'
|
||||
- path: providers/dns/dns_providers.go
|
||||
text: "Function 'NewDNSChallengeProviderByName' has too many statements"
|
||||
- path: cmd/flags.go
|
||||
text: "Function 'CreateFlags' is too long"
|
||||
- path: certificate/certificates.go
|
||||
text: "Function 'GetOCSP' is too long"
|
||||
- path: providers/dns/otc/client.go
|
||||
text: "Function 'loginRequest' is too long"
|
||||
- path: providers/dns/gandi/gandi.go
|
||||
text: "Function 'Present' is too long"
|
||||
- path: cmd/zz_gen_cmd_dnshelp.go
|
||||
linters:
|
||||
- gocyclo
|
||||
- funlen
|
||||
- path: providers/dns/checkdomain/internal/types.go
|
||||
text: '`payed` is a misspelling of `paid`'
|
||||
- path: providers/dns/namecheap/namecheap_test.go
|
||||
text: 'cognitive complexity (\d+) of func `TestDNSProvider_getHosts` is high'
|
||||
- path: platform/tester/env_test.go
|
||||
linters:
|
||||
- thelper
|
||||
- path: providers/dns/oraclecloud/oraclecloud_test.go
|
||||
text: 'SA1019: x509.EncryptPEMBlock has been deprecated since Go 1.16'
|
||||
- path: challenge/http01/domain_matcher.go
|
||||
text: 'yodaStyleExpr'
|
||||
- path: providers/dns/dns_providers.go
|
||||
text: 'Function name: NewDNSChallengeProviderByName,'
|
||||
- path: providers/dns/sakuracloud/wrapper.go
|
||||
text: 'mu is a global variable'
|
||||
- path: providers/dns/hosttech/internal/client_test.go
|
||||
text: 'Duplicate words \(0\) found'
|
||||
- path: cmd/cmd_renew.go
|
||||
text: 'cyclomatic complexity 16 of func `renewForDomains` is high'
|
||||
|
135
.goreleaser.yml
Normal file
135
.goreleaser.yml
Normal file
|
@ -0,0 +1,135 @@
|
|||
project_name: lego
|
||||
|
||||
builds:
|
||||
- binary: lego
|
||||
|
||||
main: ./cmd/lego/main.go
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
flags:
|
||||
- -trimpath
|
||||
ldflags:
|
||||
- -s -w -X main.version={{.Version}}
|
||||
|
||||
goos:
|
||||
- windows
|
||||
- darwin
|
||||
- linux
|
||||
- freebsd
|
||||
- openbsd
|
||||
- solaris
|
||||
goarch:
|
||||
- amd64
|
||||
- 386
|
||||
- arm
|
||||
- arm64
|
||||
- mips
|
||||
- mipsle
|
||||
- mips64
|
||||
- mips64le
|
||||
goarm:
|
||||
- 7
|
||||
- 6
|
||||
- 5
|
||||
gomips:
|
||||
- hardfloat
|
||||
- softfloat
|
||||
|
||||
ignore:
|
||||
- goos: darwin
|
||||
goarch: 386
|
||||
- goos: openbsd
|
||||
goarch: arm
|
||||
|
||||
archives:
|
||||
- id: lego
|
||||
name_template: '{{ .ProjectName }}_v{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}{{ if .Mips }}_{{ .Mips }}{{ end }}'
|
||||
format: tar.gz
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
files:
|
||||
- LICENSE
|
||||
- CHANGELOG.md
|
||||
|
||||
docker_manifests:
|
||||
- name_template: 'goacme/lego:{{ .Tag }}'
|
||||
image_templates:
|
||||
- 'goacme/lego:{{ .Tag }}-amd64'
|
||||
- 'goacme/lego:{{ .Tag }}-arm64'
|
||||
- 'goacme/lego:{{ .Tag }}-armv7'
|
||||
- name_template: 'goacme/lego:latest'
|
||||
image_templates:
|
||||
- 'goacme/lego:{{ .Tag }}-amd64'
|
||||
- 'goacme/lego:{{ .Tag }}-arm64'
|
||||
- 'goacme/lego:{{ .Tag }}-armv7'
|
||||
- name_template: 'goacme/lego:v{{ .Major }}.{{ .Minor }}'
|
||||
image_templates:
|
||||
- 'goacme/lego:v{{ .Major }}.{{ .Minor }}-amd64'
|
||||
- 'goacme/lego:v{{ .Major }}.{{ .Minor }}-arm64'
|
||||
- 'goacme/lego:v{{ .Major }}.{{ .Minor }}-armv7'
|
||||
|
||||
dockers:
|
||||
- use: buildx
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
dockerfile: buildx.Dockerfile
|
||||
image_templates:
|
||||
- 'goacme/lego:latest-amd64'
|
||||
- 'goacme/lego:{{ .Tag }}-amd64'
|
||||
- 'goacme/lego:v{{ .Major }}.{{ .Minor }}-amd64'
|
||||
build_flag_templates:
|
||||
- '--pull'
|
||||
# https://github.com/opencontainers/image-spec/blob/main/annotations.md#pre-defined-annotation-keys
|
||||
- '--label=org.opencontainers.image.title={{.ProjectName}}'
|
||||
- '--label=org.opencontainers.image.description=Lets Encrypt/ACME client and library written in Go'
|
||||
- '--label=org.opencontainers.image.source={{.GitURL}}'
|
||||
- '--label=org.opencontainers.image.url={{.GitURL}}'
|
||||
- '--label=org.opencontainers.image.documentation=https://go-acme.github.io/lego'
|
||||
- '--label=org.opencontainers.image.created={{.Date}}'
|
||||
- '--label=org.opencontainers.image.revision={{.FullCommit}}'
|
||||
- '--label=org.opencontainers.image.version={{.Version}}'
|
||||
- '--platform=linux/amd64'
|
||||
|
||||
- use: buildx
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
dockerfile: buildx.Dockerfile
|
||||
image_templates:
|
||||
- 'goacme/lego:latest-arm64'
|
||||
- 'goacme/lego:{{ .Tag }}-arm64'
|
||||
- 'goacme/lego:v{{ .Major }}.{{ .Minor }}-arm64'
|
||||
build_flag_templates:
|
||||
- '--pull'
|
||||
# https://github.com/opencontainers/image-spec/blob/main/annotations.md#pre-defined-annotation-keys
|
||||
- '--label=org.opencontainers.image.title={{.ProjectName}}'
|
||||
- '--label=org.opencontainers.image.description=Lets Encrypt/ACME client and library written in Go'
|
||||
- '--label=org.opencontainers.image.source={{.GitURL}}'
|
||||
- '--label=org.opencontainers.image.url={{.GitURL}}'
|
||||
- '--label=org.opencontainers.image.documentation=https://go-acme.github.io/lego'
|
||||
- '--label=org.opencontainers.image.created={{.Date}}'
|
||||
- '--label=org.opencontainers.image.revision={{.FullCommit}}'
|
||||
- '--label=org.opencontainers.image.version={{.Version}}'
|
||||
- '--platform=linux/arm64'
|
||||
|
||||
- use: buildx
|
||||
goos: linux
|
||||
goarch: arm
|
||||
goarm: '7'
|
||||
dockerfile: buildx.Dockerfile
|
||||
image_templates:
|
||||
- 'goacme/lego:latest-armv7'
|
||||
- 'goacme/lego:{{ .Tag }}-armv7'
|
||||
- 'goacme/lego:v{{ .Major }}.{{ .Minor }}-armv7'
|
||||
build_flag_templates:
|
||||
- '--pull'
|
||||
# https://github.com/opencontainers/image-spec/blob/main/annotations.md#pre-defined-annotation-keys
|
||||
- '--label=org.opencontainers.image.title={{.ProjectName}}'
|
||||
- '--label=org.opencontainers.image.description=Lets Encrypt/ACME client and library written in Go'
|
||||
- '--label=org.opencontainers.image.source={{.GitURL}}'
|
||||
- '--label=org.opencontainers.image.url={{.GitURL}}'
|
||||
- '--label=org.opencontainers.image.documentation=https://go-acme.github.io/lego'
|
||||
- '--label=org.opencontainers.image.created={{.Date}}'
|
||||
- '--label=org.opencontainers.image.revision={{.FullCommit}}'
|
||||
- '--label=org.opencontainers.image.version={{.Version}}'
|
||||
- '--platform=linux/arm/v7'
|
59
404.html
59
404.html
|
@ -1,59 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en" class="js csstransforms3d">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8"> <meta name="description" content="">
|
||||
<meta name="author" content="Lego Team">
|
||||
<link rel="icon" href="/lego/images/favicon.png" type="image/png">
|
||||
|
||||
<title>404 Page not found</title>
|
||||
|
||||
|
||||
<link href="/lego/css/nucleus.css?1690289131" rel="stylesheet">
|
||||
<link href="/lego/css/fontawesome-all.min.css?1690289131" rel="stylesheet">
|
||||
<link href="/lego/css/hybrid.css?1690289131" rel="stylesheet">
|
||||
<link href="/lego/css/featherlight.min.css?1690289131" rel="stylesheet">
|
||||
<link href="/lego/css/perfect-scrollbar.min.css?1690289131" rel="stylesheet">
|
||||
<link href="/lego/css/theme.css?1690289131" rel="stylesheet">
|
||||
<link href="/lego/css/hugo-theme.css?1690289131" rel="stylesheet">
|
||||
|
||||
<link href="/lego/css/theme-blue.css?1690289131" rel="stylesheet">
|
||||
|
||||
<style>
|
||||
:root #header + #content > #left > #rlblock_left {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
p,
|
||||
li,
|
||||
ul {
|
||||
text-align: center
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style-type: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
</head>
|
||||
|
||||
<body class="" data-url="/">
|
||||
|
||||
<section id="body" style="margin-left:0px;">
|
||||
<div id="overlay"></div>
|
||||
<div id="chapter">
|
||||
<div id="body-inner">
|
||||
<h1>Error</h1>
|
||||
<p>
|
||||
</p>
|
||||
<p>Woops. Looks like this page doesn't exist ¯\_(ツ)_/¯.</p>
|
||||
<p></p>
|
||||
<p><a href='/lego/'>Go to homepage</a></p>
|
||||
<p><img src='/images/gopher-404.jpg' style="width:50%" alt="Page not found!"></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</section>
|
||||
</body>
|
||||
|
||||
</html>
|
999
CHANGELOG.md
Normal file
999
CHANGELOG.md
Normal file
|
@ -0,0 +1,999 @@
|
|||
# Changelog
|
||||
|
||||
## [v4.13.2] - 2023-07-21
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** servercow: fix regression
|
||||
|
||||
## [v4.13.1] - 2023-07-20
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS provider for IPv64
|
||||
- **[dnsprovider]** Add DNS provider for Metaname
|
||||
- **[dnsprovider]** Add DNS provider for RcodeZero
|
||||
- **[dnsprovider]** Add DNS provider for Efficient IP
|
||||
- **[dnsprovider]** azure: new implementation based on the new API client
|
||||
- **[lib]** Experimental option to force DNS queries to use TCP
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** cloudflare: update api client to v0.70.0
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider,cname]** fix: ensure case-insensitive comparison of CNAME records
|
||||
- **[cli]** fix: list command
|
||||
- **[lib]** fix: ARI explanationURL
|
||||
|
||||
## [v4.13.0] - 2023-07-20
|
||||
|
||||
Cancelled due to a CI issue (no space left on device).
|
||||
|
||||
## [v4.12.2] - 2023-06-19
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** dnsmadeeasy: fix DeleteRecord
|
||||
- **[lib]** fix: read status code from response
|
||||
|
||||
## [v4.12.1] - 2023-06-06
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** pdns: fix record value
|
||||
|
||||
## [v4.12.0] - 2023-05-28
|
||||
|
||||
### Added:
|
||||
- **[lib,cli]** Initial ACME Renewal Info (ARI) Implementation
|
||||
- **[dnsprovider]** Add DNS provider for Derak Cloud
|
||||
- **[dnsprovider]** route53: pass ExternalID property to STS:AssumeRole API operation
|
||||
- **[lib,cli]** Support custom duration for certificate
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** Refactor DNS provider and client implementations
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** autodns: fixes wrong zone in api call if CNAME is used
|
||||
- **[cli]** fix: archive only domain-related files on revoke
|
||||
|
||||
## [v4.11.0] - 2023-05-02
|
||||
|
||||
### Added:
|
||||
- **[lib]** Support for certificate with raw IP SAN (RFC8738)
|
||||
- **[dnsprovider]** Add Brandit.com as DNS provider
|
||||
- **[dnsprovider]** Add DNS provider for Bunny
|
||||
- **[dnsprovider]** Add DNS provider for Nodion
|
||||
- **[dnsprovider]** Add Google Domains as DNS provider
|
||||
- **[dnsprovider]** Add DNS provider for Plesk
|
||||
|
||||
### Changed:
|
||||
- **[cli]** feat: add LEGO_CERT_PEM_PATH and LEGO_CERT_PFX_PATH to run hook
|
||||
- **[lib,cli]** feat: add RSA 3072
|
||||
- **[dnsprovider]** gcloud: update google APIs to latest version
|
||||
- **[lib,dnsprovider,cname]** chore: replace GetRecord by GetChallengeInfo
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** rimuhosting: fix API base URL
|
||||
|
||||
## [v4.10.2] - 2023-02-26
|
||||
|
||||
Fix Docker image builds.
|
||||
|
||||
## [v4.10.1] - 2023-02-25
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider,cname]** acmedns: fix CNAME support
|
||||
- **[dnsprovider]** dynu: fix subdomain support
|
||||
|
||||
## [v4.10.0] - 2023-02-10
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS provider for dnsHome.de
|
||||
- **[dnsprovider]** Add DNS provider for Liara
|
||||
- **[dnsprovider]** Add DNS provider for UltraDNS
|
||||
- **[dnsprovider]** Add DNS provider for Websupport
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** ibmcloud: add support for subdomains
|
||||
- **[dnsprovider]** infomaniak: CNAME support
|
||||
- **[dnsprovider]** namesilo: add cleanup before add a DNS record
|
||||
- **[dnsprovider]** route53: Allow static credentials to be supplied
|
||||
- **[dnsprovider]** tencentcloud: support punycode domain
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** alidns: filter on record type
|
||||
- **[dnsprovider]** arvancloud: replace arvancloud.com by arvancloud.ir
|
||||
- **[dnsprovider]** hetzner: improve zone ID detection
|
||||
- **[dnsprovider]** luadns: removed dot suffix from authzone while searching for zone
|
||||
- **[dnsprovider]** pdns: fix usage of notify only when zone kind is Master or Slave
|
||||
- **[dnsprovider]** return an error when extracting record name
|
||||
|
||||
## [v4.9.1] - 2022-11-25
|
||||
|
||||
### Changed:
|
||||
-
|
||||
- **[lib,cname]** cname: add log about CNAME entries
|
||||
- **[dnsprovider]** regru: improve error handling
|
||||
|
||||
### Fixed:
|
||||
-
|
||||
- **[dnsprovider,cname]** fix CNAME support for multiple DNS providers
|
||||
- **[dnsprovider,cname]** duckdns: fix CNAME support
|
||||
- **[dnsprovider,cname]** oraclecloud: use fqdn to resolve zone
|
||||
- **[dnsprovider]** hurricane: fix CNAME support
|
||||
- **[lib,cname]** cname: stop trying to traverse cname if none have been found
|
||||
|
||||
## [v4.9.0] - 2022-10-03
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for CIVO
|
||||
- **[dnsprovider]** Add DNS provider for VK Cloud
|
||||
- **[dnsprovider]** Add DNS provider for YandexCloud
|
||||
- **[dnsprovider]** digitalocean: configurable base URL
|
||||
- **[dnsprovider]** loopia: add configurable API endpoint
|
||||
- **[dnsprovider]** pdns: notify secondary servers after updates
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** allinkl: removed deprecated sha1 hashing
|
||||
- **[dnsprovider]** auroradns: update authentification
|
||||
- **[dnsprovider]** dnspod: deprecated. Use Tencent Cloud instead.
|
||||
- **[dnsprovider]** exoscale: migrate to API v2 endpoints
|
||||
- **[dnsprovider]** gcloud: update golang.org/x/oauth2
|
||||
- **[dnsprovider]** lightsail: cleanup
|
||||
- **[dnsprovider]** sakuracloud: update api client library
|
||||
- **[cname]** take out CNAME support from experimental features
|
||||
- **[lib,cname]** add recursive CNAME lookup support
|
||||
- **[lib]** Remove embedded issuer certificates from issued certificate if bundle is false
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** luadns: fix cname support
|
||||
- **[dnsprovider]** njalla: fix record id unmarshal error
|
||||
- **[dnsprovider]** tencentcloud: fix subdomain error
|
||||
|
||||
## [v4.8.0] - 2022-06-30
|
||||
|
||||
### Added
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Variomedia
|
||||
- **[dnsprovider]** Add NearlyFreeSpeech DNS Provider
|
||||
- **[cli]** Add a --user-agent flag to lego-cli
|
||||
|
||||
### Changed
|
||||
|
||||
- new logo
|
||||
- **[cli]** feat: sleep at renewal
|
||||
- **[cli]** cli/renew: skip random sleep if stdout is a terminal
|
||||
- **[dnsprovider]** hetzner: set min TTL to 60s
|
||||
- **[docs]** refactoring and cleanup
|
||||
|
||||
## [v4.7.0] - 2022-05-27
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for iwantmyname
|
||||
- **[dnsprovider]** Add DNS Provider for IIJ DNS Platform Service
|
||||
- **[dnsprovider]** Add DNS provider for Vercel
|
||||
- **[dnsprovider]** route53: add assume role ARN
|
||||
- **[dnsprovider]** dnsimple: add debug option
|
||||
- **[cli]** feat: add `LEGO_CERT_PEM_PATH` and `LEGO_CERT_PFX_PATH`
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** gcore: change dns api url
|
||||
- **[dnsprovider]** bluecat: rewrite provider implementation
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** rfc2136: fix TSIG secret
|
||||
- **[dnsprovider]** tencentcloud: fix InvalidParameter.DomainInvalid error when using DNS challenges
|
||||
- **[lib]** fix: panic in certcrypto.ParsePEMPrivateKey
|
||||
|
||||
## [v4.6.0] - 2022-01-18
|
||||
|
||||
### Added
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for UKFast SafeDNS
|
||||
- **[dnsprovider]** Add DNS Provider for Tencent Cloud
|
||||
- **[dnsprovider]** azure: add support for Azure Private Zone DNS
|
||||
- **[dnsprovider]** exec: add sequence interval
|
||||
- **[cli]** Add a `--pfx`, and `--pfx.pas`s option to generate a PKCS#12 (`.pfx`) file.
|
||||
- **[lib]** Extended support of cert pool (`LEGO_CA_CERTIFICATES` and `LEGO_CA_SYSTEM_CERT_POOL`)
|
||||
- **[lib,httpprovider]** added uds capability to http challenge server
|
||||
|
||||
### Changed
|
||||
|
||||
- **[lib]** Extend validity of TLS-ALPN-01 certificates to 365 days
|
||||
- **[lib,cli]** Allows defining the reason for the certificate revocation
|
||||
|
||||
### Fixed
|
||||
|
||||
- **[dnsprovider]** mythicbeasts: fix token expiration
|
||||
- **[dnsprovider]** rackspace: change zone ID to string
|
||||
|
||||
## [v4.5.3] - 2021-09-06
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[lib,cli]** fix: missing preferred chain param for renew request
|
||||
|
||||
## [v4.5.2] - 2021-09-01
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for all-inkl
|
||||
- **[dnsprovider]** Add DNS provider for Epik
|
||||
- **[dnsprovider]** Add DNS provider for freemyip.com
|
||||
- **[dnsprovider]** Add DNS provider for g-core labs
|
||||
- **[dnsprovider]** Add DNS provider for hosttech
|
||||
- **[dnsprovider]** Add DNS Provider for IBM Cloud (SoftLayer)
|
||||
- **[dnsprovider]** Add DNS provider for Internet.bs
|
||||
- **[dnsprovider]** Add DNS provider for nicmanager
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** alidns: support ECS instance RAM role
|
||||
- **[dnsprovider]** alidns: support sts token credential
|
||||
- **[dnsprovider]** azure: zone name as environment variable
|
||||
- **[dnsprovider]** ovh: follow cname
|
||||
- **[lib,cli]** Add AlwaysDeactivateAuthorizations flag to ObtainRequest
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** infomaniak: fix subzone support
|
||||
- **[dnsprovider]** edgedns: fix Present and CleanUp logic
|
||||
- **[dnsprovider]** lightsail: wrong Region env var name
|
||||
- **[lib]** lib: fix backoff in SolverManager
|
||||
- **[lib]** lib: use permanent error instead of context cancellation
|
||||
- **[dnsprovider]** desec: bump to v0.6.0
|
||||
|
||||
## [v4.5.1] - 2021-09-01
|
||||
|
||||
Cancelled due to a CI issue, replaced by v4.5.2.
|
||||
|
||||
## [v4.5.0] - 2021-09-30
|
||||
|
||||
Cancelled due to a CI issue, replaced by v4.5.2.
|
||||
|
||||
## [v4.4.0] - 2021-06-08
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Infoblox
|
||||
- **[dnsprovider]** Add DNS provider for Porkbun
|
||||
- **[dnsprovider]** Add DNS provider for Simply.com
|
||||
- **[dnsprovider]** Add DNS provider for Sonic
|
||||
- **[dnsprovider]** Add DNS provider for VinylDNS
|
||||
- **[dnsprovider]** Add DNS provider for wedos
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[cli]** log: Use stderr instead of stdout.
|
||||
- **[dnsprovider]** hostingde: autodetection of the zone name.
|
||||
- **[dnsprovider]** scaleway: use official SDK
|
||||
- **[dnsprovider]** powerdns: several improvements
|
||||
- **[lib]** lib: improve wait.For returns.
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** hurricane: add API rate limiter.
|
||||
- **[dnsprovider]** hurricane: only treat first word of response body as response code
|
||||
- **[dnsprovider]** exoscale: fix DNS provider debugging
|
||||
- **[dnsprovider]** wedos: fix api call parameters
|
||||
- **[dnsprovider]** nifcloud: Get zone info from dns01.FindZoneByFqdn
|
||||
- **[cli,lib]** csr: Support the type `NEW CERTIFICATE REQUEST`
|
||||
|
||||
## [v4.3.1] - 2021-03-12
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** exoscale: fix dependency version.
|
||||
|
||||
## [v4.3.0] - 2021-03-10
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Njalla
|
||||
- **[dnsprovider]** Add DNS provider for Domeneshop
|
||||
- **[dnsprovider]** Add DNS provider for Hurricane Electric
|
||||
- **[dnsprovider]** designate: support for Openstack Application Credentials
|
||||
- **[dnsprovider]** edgedns: support for .edgerc file
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** infomaniak: Make error message more meaningful
|
||||
- **[dnsprovider]** cloudns: Improve reliability
|
||||
- **[dnsprovider]** rfc2163: Removed support for MD5 algorithm. The default algorithm is now SHA1.
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** desec: fix error with default TTL
|
||||
- **[dnsprovider]** mythicbeasts: implement `ProviderTimeout`
|
||||
- **[dnsprovider]** dnspod: improve search accuracy when a domain have more than 100 records
|
||||
- **[lib]** Increase HTTP client timeouts
|
||||
- **[lib]** preferred chain only match root name
|
||||
|
||||
## [v4.2.0] - 2021-01-24
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Loopia
|
||||
- **[dnsprovider]** Add DNS provider for Ionos.
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** acme-dns: update cpu/goacmedns to v0.1.1.
|
||||
- **[dnsprovider]** inwx: Increase propagation timeout to 360s to improve robustness
|
||||
- **[dnsprovider]** vultr: Update to govultr v2 API
|
||||
- **[dnsprovider]** pdns: get exact zone instead of all zones
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** vult, dnspod: fix default HTTP timeout.
|
||||
- **[dnsprovider]** pdns: URL request creation.
|
||||
- **[lib]** errors: Fix instance not being printed
|
||||
|
||||
## [v4.1.3] - 2020-11-25
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** azure: fix error handling.
|
||||
|
||||
## [v4.1.2] - 2020-11-21
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[lib]** fix: preferred chain support.
|
||||
|
||||
## [v4.1.1] - 2020-11-19
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** otc: select correct zone if multiple returned
|
||||
- **[dnsprovider]** azure: fix target must be a non-nil pointer
|
||||
|
||||
## [v4.1.0] - 2020-11-06
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Infomaniak
|
||||
- **[dnsprovider]** joker: add support for SVC API
|
||||
- **[dnsprovider]** gcloud: add an option to allow the use of private zones
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** rfc2136: ensure TSIG algorithm is fully qualified
|
||||
- **[dnsprovider]** designate: Deprecate OS_TENANT_NAME as required field
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[lib]** acme/api: use postAsGet instead of post for AccountService.Get
|
||||
- **[lib]** fix: use http.Header.Set method instead of Add.
|
||||
|
||||
## [v4.0.1] - 2020-09-03
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** exoscale: change dependency version.
|
||||
|
||||
## [v4.0.0] - 2020-09-02
|
||||
|
||||
### Added:
|
||||
|
||||
- **[cli], [lib]** Support "alternate" certificate links for selecting different signing Chains
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[cli]** Replaces `ec384` by `ec256` as default key-type
|
||||
- **[lib]** Changes `ObtainForCSR` method signature
|
||||
|
||||
### Removed:
|
||||
|
||||
- **[dnsprovider]** Replaces FastDNS by EdgeDNS
|
||||
- **[dnsprovider]** Removes old Linode provider
|
||||
- **[lib]** Removes `AddPreCheck` function
|
||||
|
||||
## [v3.9.0] - 2020-09-01
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add Akamai Edgedns. Deprecate FastDNS
|
||||
- **[dnsprovider]** Add DNS provider for HyperOne
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** designate: add support for Openstack clouds.yaml
|
||||
- **[dnsprovider]** azure: allow selecting environments
|
||||
- **[dnsprovider]** desec: applies API rate limits.
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** namesilo: fix cleanup.
|
||||
|
||||
## [v3.8.0] - 2020-07-02
|
||||
|
||||
### Added:
|
||||
|
||||
- **[cli]** cli: add hook on the run command.
|
||||
- **[dnsprovider]** inwx: Two-Factor-Authentication
|
||||
- **[dnsprovider]** Add DNS provider for ArvanCloud
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** vultr: bumping govultr version
|
||||
- **[dnsprovider]** desec: improve error logs.
|
||||
- **[lib]** Ensures the return of a location during account updates
|
||||
- **[dnsprovider]** route53: Document all AWS credential environment variables
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** stackpath: fix subdomain support.
|
||||
- **[dnsprovider]** arvandcloud: fix record name.
|
||||
- **[dnsprovider]** fix: multi-va.
|
||||
- **[dnsprovider]** constellix: fix search records API call.
|
||||
- **[dnsprovider]** hetzner: fix record name.
|
||||
- **[lib]** Registrar.ResolveAccountByKey: Fix malformed request
|
||||
|
||||
## [v3.7.0] - 2020-05-11
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Netlify.
|
||||
- **[dnsprovider]** Add DNS provider for deSEC.io
|
||||
- **[dnsprovider]** Add DNS provider for LuaDNS
|
||||
- **[dnsprovider]** Adding Hetzner DNS provider
|
||||
- **[dnsprovider]** Add DNS provider for Mythic beasts DNSv2
|
||||
- **[dnsprovider]** Add DNS provider for Yandex.
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** Upgrade DNSimple client to 0.60.0
|
||||
- **[dnsprovider]** update aws sdk
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** autodns: removes TXT records during CleanUp.
|
||||
- **[dnsprovider]** Fix exoscale HTTP timeout
|
||||
- **[cli]** fix: renew path information.
|
||||
- **[cli]** Fix account storage location warning message
|
||||
|
||||
## [v3.6.0] - 2020-04-24
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for CloudDNS.
|
||||
- **[dnsprovider]** alicloud: add support for domain with punycode
|
||||
- **[dnsprovider]** cloudns: Add subuser support
|
||||
- **[cli]** Information about renewed certificates are now passed to the renew hook
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** acmedns: Update cpu/goacmedns v0.0.1 -> v0.0.2
|
||||
- **[dnsprovider]** alicloud: update sdk dependency version to v1.61.112
|
||||
- **[dnsprovider]** azure: Allow for the use of MSI
|
||||
- **[dnsprovider]** constellix: improve challenge.
|
||||
- **[dnsprovider]** godaddy: allow parallel solve.
|
||||
- **[dnsprovider]** namedotcom: get the actual registered domain so we can remove just that from the hostname to be created
|
||||
- **[dnsprovider]** transip: updated the client to v6
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** ns1: fix missing domain in log
|
||||
- **[dnsprovider]** rimuhosting: use HTTP client from config.
|
||||
|
||||
## [v3.5.0] - 2020-03-15
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Dynu.
|
||||
- **[dnsprovider]** Add DNS provider for reg.ru
|
||||
- **[dnsprovider]** Add DNS provider for Zonomi and RimuHosting.
|
||||
- **[cli]** Building binaries for arm 6 and 5
|
||||
- **[cli]** Uses CGO_ENABLED=0
|
||||
- **[cli]** Multi-arch Docker image.
|
||||
- **[cli]** Adds `--name` flag to list command.
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[lib]** lib: Improve cleanup log messages.
|
||||
- **[lib]** Wrap errors.
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** azure: pass AZURE_CLIENT_SECRET_FILE to autorest.Authorizer
|
||||
- **[dnsprovider]** gcloud: fixes issues when used with GKE Workload Identity
|
||||
- **[dnsprovider]** oraclecloud: fix subdomain support
|
||||
|
||||
## [v3.4.0] - 2020-02-25
|
||||
|
||||
### Added:
|
||||
|
||||
- **[dnsprovider]** Add DNS provider for Constellix
|
||||
- **[dnsprovider]** Add DNS provider for Servercow.
|
||||
- **[dnsprovider]** Add DNS provider for Scaleway
|
||||
- **[cli]** Add "LEGO_PATH" environment variable
|
||||
|
||||
### Changed:
|
||||
|
||||
- **[dnsprovider]** route53: allow custom client to be provided
|
||||
- **[dnsprovider]** namecheap: allow external domains
|
||||
- **[dnsprovider]** namecheap: add sandbox support.
|
||||
- **[dnsprovider]** ovh: Improve provider documentation
|
||||
- **[dnsprovider]** route53: Improve provider documentation
|
||||
|
||||
### Fixed:
|
||||
|
||||
- **[dnsprovider]** zoneee: fix subdomains.
|
||||
- **[dnsprovider]** designate: Don't clean up managed records like SOA and NS
|
||||
- **[dnsprovider]** dnspod: update lib.
|
||||
- **[lib]** crypto: Treat CommonName as optional
|
||||
- **[lib]** chore: update cenkalti/backoff to v4.
|
||||
|
||||
## [v3.3.0] - 2020-01-08
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS provider for Checkdomain
|
||||
- **[lib]** Add support to update account
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** gcloud: Auto-detection of the project ID.
|
||||
- **[lib]** Successfully parse private key PEM blocks
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** Update dnspod, because of API breaking changes.
|
||||
|
||||
## [v3.2.0] - 2019-11-10
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add support for autodns
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** httpreq: Allow use environment vars from a `_FILE` file
|
||||
- **[lib]** Don't deactivate valid authorizations
|
||||
- **[lib]** Expose more SOA fields found by dns01.FindZoneByFqdn
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** use token as unique ID.
|
||||
|
||||
## [v3.1.0] - 2019-10-07
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS provider for Liquid Web
|
||||
- **[dnsprovider]** cloudflare: add support for API tokens
|
||||
- **[cli]** feat: ease operation behind proxy servers
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** cloudflare: update client
|
||||
- **[dnsprovider]** linodev4: propagation timeout configuration.
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** ovh: fix int overflow.
|
||||
- **[dnsprovider]** bindman: fix client version.
|
||||
|
||||
## [v3.0.2] - 2019-08-15
|
||||
|
||||
### Fixed:
|
||||
- Invalid pseudo version (related to Cloudflare client).
|
||||
|
||||
## [v3.0.1] - 2019-08-14
|
||||
|
||||
There was a problem when creating the tag v3.0.1, this tag has been invalidate.
|
||||
|
||||
## [v3.0.0] - 2019-08-05
|
||||
|
||||
### Changed:
|
||||
- migrate to go module (new import github.com/go-acme/lego/v3/)
|
||||
- update DNS clients
|
||||
|
||||
## [v2.7.2] - 2019-07-30
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** vultr: quote TXT record
|
||||
|
||||
## [v2.7.1] - 2019-07-22
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** vultr: invalid record type.
|
||||
|
||||
## [v2.7.0] - 2019-07-17
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS provider for namesilo
|
||||
- **[dnsprovider]** Add DNS provider for versio.nl
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** Update DNS providers libs.
|
||||
- **[dnsprovider]** joker: support username and password.
|
||||
- **[dnsprovider]** Vultr: Switch to official client
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** otc: Prevent sending empty body.
|
||||
|
||||
## [v2.6.0] - 2019-05-27
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add support for Joker.com DMAPI
|
||||
- **[dnsprovider]** Add support for Bindman DNS provider
|
||||
- **[dnsprovider]** Add support for EasyDNS
|
||||
- **[lib]** Get an existing certificate by URL
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** digitalocean: LEGO_EXPERIMENTAL_CNAME_SUPPORT support
|
||||
- **[dnsprovider]** gcloud: Use fqdn to get zone Present/CleanUp
|
||||
- **[dnsprovider]** exec: serial behavior
|
||||
- **[dnsprovider]** manual: serial behavior.
|
||||
- **[dnsprovider]** Strip newlines when reading environment variables from `_FILE` suffixed files.
|
||||
|
||||
### Fixed:
|
||||
- **[cli]** fix: cli disable-cp option.
|
||||
- **[dnsprovider]** gcloud: fix zone visibility.
|
||||
|
||||
## [v2.5.0] - 2019-04-17
|
||||
|
||||
### Added:
|
||||
- **[cli]** Adds renew hook
|
||||
- **[dnsprovider]** Adds 'Since' to DNS providers documentation
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** gcloud: use public DNS zones
|
||||
- **[dnsprovider]** route53: enhance documentation.
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** cloudns: fix TTL and status validation
|
||||
- **[dnsprovider]** sakuracloud: supports concurrent update
|
||||
- **[dnsprovider]** Disable authz when solve fail.
|
||||
- Add tzdata to the Docker image.
|
||||
|
||||
## [v2.4.0] - 2019-03-25
|
||||
|
||||
- Migrate from xenolf/lego to go-acme/lego.
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS Provider for Domain Offensive (do.de)
|
||||
- **[dnsprovider]** Adds information about '_FILE' suffix.
|
||||
|
||||
### Fixed:
|
||||
- **[cli,dnsprovider]** Add 'manual' provider to the output of dnshelp
|
||||
- **[dnsprovider]** hostingde: Use provided ZoneName instead of domain
|
||||
- **[dnsprovider]** pdns: fix wildcard with SANs
|
||||
|
||||
## [v2.3.0] - 2019-03-11
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS Provider for ClouDNS.net
|
||||
- **[dnsprovider]** Add DNS Provider for Oracle Cloud
|
||||
|
||||
### Changed:
|
||||
- **[cli]** Adds log when no renewal.
|
||||
- **[dnsprovider,lib]** Add a mechanism to wrap a PreCheckFunc
|
||||
- **[dnsprovider]** oraclecloud: better way to get private key.
|
||||
- **[dnsprovider]** exoscale: update library
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** OVH: Refresh zone after deleting challenge record
|
||||
- **[dnsprovider]** oraclecloud: ttl config and timeout
|
||||
- **[dnsprovider]** hostingde: fix client fails if customer has no access to dns-groups
|
||||
- **[dnsprovider]** vscale: getting sub-domain
|
||||
- **[dnsprovider]** selectel: getting sub-domain
|
||||
- **[dnsprovider]** vscale: fix TXT records clean up
|
||||
- **[dnsprovider]** selectel: fix TXT records clean up
|
||||
|
||||
## [v2.2.0] - 2019-02-08
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add support for Openstack Designate as a DNS provider
|
||||
- **[dnsprovider]** gcloud: Option to specify gcloud service account json by env as string
|
||||
- **[experimental feature]** Resolve CNAME when creating dns-01 challenge. To enable: set `LEGO_EXPERIMENTAL_CNAME_SUPPORT` to `true`.
|
||||
|
||||
### Changed:
|
||||
- **[cli]** Applies Let’s Encrypt’s recommendation about renew. The option `--days` of the command `renew` has a new default value (`30`)
|
||||
- **[lib]** Uses a jittered exponential backoff
|
||||
|
||||
### Fixed:
|
||||
- **[cli]** CLI and key type.
|
||||
- **[dnsprovider]** httpreq: Endpoint with path.
|
||||
- **[dnsprovider]** fastdns: Do not overwrite existing TXT records
|
||||
- Log wildcard domain correctly in validation
|
||||
|
||||
## [v2.1.0] - 2019-01-24
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add support for zone.ee as a DNS provider.
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** nifcloud: Change DNS base url.
|
||||
- **[dnsprovider]** gcloud: More detailed information about Google Cloud DNS.
|
||||
|
||||
### Fixed:
|
||||
- **[lib]** fix: OCSP, set HTTP client.
|
||||
- **[dnsprovider]** alicloud: fix pagination.
|
||||
- **[dnsprovider]** namecheap: fix panic.
|
||||
|
||||
## [v2.0.0] - 2019-01-09
|
||||
|
||||
### Added:
|
||||
- **[cli,lib]** Option to disable the complete propagation Requirement
|
||||
- **[lib,cli]** Support non-ascii domain name (punnycode)
|
||||
- **[cli,lib]** Add configurable timeout when obtaining certificates
|
||||
- **[cli]** Archive revoked certificates
|
||||
- **[cli]** Add command to list certificates.
|
||||
- **[cli]** support for renew with CSR
|
||||
- **[cli]** add SAN on renew
|
||||
- **[lib]** Adds `Remove` for challenges
|
||||
- **[lib]** Add version to xenolf-acme in User-Agent.
|
||||
- **[dnsprovider]** The ability for a DNS provider to solve the challenge sequentially
|
||||
- **[dnsprovider]** Add DNS provider for "HTTP request".
|
||||
- **[dnsprovider]** Add DNS Provider for Vscale
|
||||
- **[dnsprovider]** Add DNS Provider for TransIP
|
||||
- **[dnsprovider]** Add DNS Provider for inwx
|
||||
- **[dnsprovider]** alidns: add support to handle more than 20 domains
|
||||
|
||||
### Changed:
|
||||
- **[lib]** Check all challenges in a predictable order
|
||||
- **[lib]** Poll authz URL instead of challenge URL
|
||||
- **[lib]** Check all nameservers in a predictable order
|
||||
- **[lib]** Logs every iteration of waiting for the propagation
|
||||
- **[cli]** `--http`: enable HTTP challenge **important**
|
||||
- **[cli]** `--http.port`: previously named `--http`
|
||||
- **[cli]** `--http.webroot`: previously named `--webroot`
|
||||
- **[cli]** `--http.memcached-host`: previously named `--memcached-host`
|
||||
- **[cli]** `--tls`: enable TLS challenge **important**
|
||||
- **[cli]** `--tls.port`: previously named `--tls`
|
||||
- **[cli]** `--dns.resolvers`: previously named `--dns-resolvers`
|
||||
- **[cli]** the option `--days` of the command `renew` has default value (`15`)
|
||||
- **[dnsprovider]** gcloud: Use GCE_PROJECT for project always, if specified
|
||||
|
||||
### Removed:
|
||||
- **[lib]** Remove `SetHTTP01Address`
|
||||
- **[lib]** Remove `SetTLSALPN01Address`
|
||||
- **[lib]** Remove `Exclude`
|
||||
- **[cli]** Remove `--exclude`, `-x`
|
||||
|
||||
### Fixed:
|
||||
- **[lib]** Fixes revocation for subdomains and non-ascii domains
|
||||
- **[lib]** Disable pending authorizations
|
||||
- **[dnsprovider]** transip: concurrent access to the API.
|
||||
- **[dnsprovider]** gcloud: fix for wildcard
|
||||
- **[dnsprovider]** Azure: Do not overwrite existing TXT records
|
||||
- **[dnsprovider]** fix: Cloudflare error.
|
||||
|
||||
## [v1.2.0] - 2018-11-04
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS Provider for ConoHa DNS
|
||||
- **[dnsprovider]** Add DNS Provider for MyDNS.jp
|
||||
- **[dnsprovider]** Add DNS Provider for Selectel
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** netcup: make unmarshalling of api-responses more lenient.
|
||||
|
||||
### Changed:
|
||||
- **[dnsprovider]** aurora: change DNS client
|
||||
- **[dnsprovider]** azure: update auth to support instance metadata service
|
||||
- **[dnsprovider]** dnsmadeeasy: log response body on error
|
||||
- **[lib]** TLS-ALPN-01: Update idPeAcmeIdentifierV1, draft refs.
|
||||
- **[lib]** Do not send a JWS body when POSTing challenges.
|
||||
- **[lib]** Support POST-as-GET.
|
||||
|
||||
## [v1.1.0] - 2018-10-16
|
||||
|
||||
### Added:
|
||||
- **[lib]** TLS-ALPN-01 Challenge
|
||||
- **[cli]** Add filename parameter
|
||||
- **[dnsprovider]** Allow to configure TTL, interval and timeout
|
||||
- **[dnsprovider]** Add support for reading DNS provider setup from files
|
||||
- **[dnsprovider]** Add DNS Provider for ACME-DNS
|
||||
- **[dnsprovider]** Add DNS Provider for ALIYUN DNS
|
||||
- **[dnsprovider]** Add DNS Provider for DreamHost
|
||||
- **[dnsprovider]** Add DNS provider for hosting.de
|
||||
- **[dnsprovider]** Add DNS Provider for IIJ
|
||||
- **[dnsprovider]** Add DNS Provider for netcup
|
||||
- **[dnsprovider]** Add DNS Provider for NIFCLOUD DNS
|
||||
- **[dnsprovider]** Add DNS Provider for SAKURA Cloud
|
||||
- **[dnsprovider]** Add DNS Provider for Stackpath
|
||||
- **[dnsprovider]** Add DNS Provider for VegaDNS
|
||||
- **[dnsprovider]** exec: add EXEC_MODE=RAW support.
|
||||
- **[dnsprovider]** cloudflare: support for CF_API_KEY and CF_API_EMAIL
|
||||
|
||||
### Fixed:
|
||||
- **[lib]** Don't trust identifiers order.
|
||||
- **[lib]** Fix missing issuer certificates from Let's Encrypt
|
||||
- **[dnsprovider]** duckdns: fix TXT record update url
|
||||
- **[dnsprovider]** duckdns: fix subsubdomain
|
||||
- **[dnsprovider]** gcloud: update findTxtRecords to use Name=fqdn and Type=TXT
|
||||
- **[dnsprovider]** lightsail: Fix Domain does not exist error
|
||||
- **[dnsprovider]** ns1: use the authoritative zone and not the domain name
|
||||
- **[dnsprovider]** ovh: check error to avoid panic due to nil client
|
||||
|
||||
### Changed:
|
||||
- **[lib]** Submit all dns records up front, then validate serially
|
||||
|
||||
## [v1.0.0] - 2018-05-30
|
||||
|
||||
### Changed:
|
||||
- **[lib]** ACME v2 Support.
|
||||
- **[dnsprovider]** Renamed `/providers/dns/googlecloud` to `/providers/dns/gcloud`.
|
||||
- **[dnsprovider]** Modified Google Cloud provider `gcloud.NewDNSProviderServiceAccount` function to extract the project id directly from the service account file.
|
||||
- **[dnsprovider]** Made errors more verbose for the Cloudflare provider.
|
||||
|
||||
## [v0.5.0] - 2018-05-29
|
||||
|
||||
### Added:
|
||||
- **[dnsprovider]** Add DNS challenge provider `exec`
|
||||
- **[dnsprovider]** Add DNS Provider for Akamai FastDNS
|
||||
- **[dnsprovider]** Add DNS Provider for Bluecat DNS
|
||||
- **[dnsprovider]** Add DNS Provider for CloudXNS
|
||||
- **[dnsprovider]** Add DNS Provider for Duck DNS
|
||||
- **[dnsprovider]** Add DNS Provider for Gandi Beta Platform (LiveDNS)
|
||||
- **[dnsprovider]** Add DNS Provider for GleSYS API
|
||||
- **[dnsprovider]** Add DNS Provider for GoDaddy
|
||||
- **[dnsprovider]** Add DNS Provider for Lightsail
|
||||
- **[dnsprovider]** Add DNS Provider for Name.com
|
||||
|
||||
### Fixed:
|
||||
- **[dnsprovider]** Azure: Added missing environment variable in the comments
|
||||
- **[dnsprovider]** PowerDNS: Fix zone URL, add leading slash.
|
||||
- **[dnsprovider]** DNSimple: Fix api
|
||||
- **[cli]** Correct help text for `--dns-resolvers` default.
|
||||
- **[cli]** renew/revoke - don't panic on wrong account.
|
||||
- **[lib]** Fix zone detection for cross-zone cnames.
|
||||
- **[lib]** Use proxies from environment when making outbound http connections.
|
||||
|
||||
### Changed:
|
||||
- **[lib]** Users of an effective top-level domain can use the DNS challenge.
|
||||
- **[dnsprovider]** Azure: Refactor to work with new Azure SDK version.
|
||||
- **[dnsprovider]** Cloudflare and Azure: Adding output of which envvars are missing.
|
||||
- **[dnsprovider]** Dyn DNS: Slightly improve provider error reporting.
|
||||
- **[dnsprovider]** Exoscale: update to latest egoscale version.
|
||||
- **[dnsprovider]** Route53: Use NewSessionWithOptions instead of deprecated New.
|
||||
|
||||
## [0.4.1] - 2017-09-26
|
||||
|
||||
### Added:
|
||||
- lib: A new DNS provider for OTC.
|
||||
- lib: The `AWS_HOSTED_ZONE_ID` environment variable for the Route53 DNS provider to directly specify the zone.
|
||||
- lib: The `RFC2136_TIMEOUT` enviroment variable to make the timeout for the RFC2136 provider configurable.
|
||||
- lib: The `GCE_SERVICE_ACCOUNT_FILE` environment variable to specify a service account file for the Google Cloud DNS provider.
|
||||
|
||||
### Fixed:
|
||||
- lib: Fixed an authentication issue with the latest Azure SDK.
|
||||
|
||||
## [0.4.0] - 2017-07-13
|
||||
|
||||
### Added:
|
||||
- CLI: The `--http-timeout` switch. This allows for an override of the default client HTTP timeout.
|
||||
- lib: The `HTTPClient` field. This allows for an override of the default HTTP timeout for library HTTP requests.
|
||||
- CLI: The `--dns-timeout` switch. This allows for an override of the default DNS timeout for library DNS requests.
|
||||
- lib: The `DNSTimeout` switch. This allows for an override of the default client DNS timeout.
|
||||
- lib: The `QueryRegistration` function on `acme.Client`. This performs a POST on the client registration's URI and gets the updated registration info.
|
||||
- lib: The `DeleteRegistration` function on `acme.Client`. This deletes the registration as currently configured in the client.
|
||||
- lib: The `ObtainCertificateForCSR` function on `acme.Client`. The function allows to request a certificate for an already existing CSR.
|
||||
- CLI: The `--csr` switch. Allows to use already existing CSRs for certificate requests on the command line.
|
||||
- CLI: The `--pem` flag. This will change the certificate output so it outputs a .pem file concatanating the .key and .crt files together.
|
||||
- CLI: The `--dns-resolvers` flag. Allows for users to override the default DNS servers used for recursive lookup.
|
||||
- lib: Added a memcached provider for the HTTP challenge.
|
||||
- CLI: The `--memcached-host` flag. This allows to use memcached for challenge storage.
|
||||
- CLI: The `--must-staple` flag. This enables OCSP must staple in the generated CSR.
|
||||
- lib: The library will now honor entries in your resolv.conf.
|
||||
- lib: Added a field `IssuerCertificate` to the `CertificateResource` struct.
|
||||
- lib: A new DNS provider for OVH.
|
||||
- lib: A new DNS provider for DNSMadeEasy.
|
||||
- lib: A new DNS provider for Linode.
|
||||
- lib: A new DNS provider for AuroraDNS.
|
||||
- lib: A new DNS provider for NS1.
|
||||
- lib: A new DNS provider for Azure DNS.
|
||||
- lib: A new DNS provider for Rackspace DNS.
|
||||
- lib: A new DNS provider for Exoscale DNS.
|
||||
- lib: A new DNS provider for DNSPod.
|
||||
|
||||
### Changed:
|
||||
- lib: Exported the `PreCheckDNS` field so library users can manage the DNS check in tests.
|
||||
- lib: The library will now skip challenge solving if a valid Authz already exists.
|
||||
|
||||
### Removed:
|
||||
- lib: The library will no longer check for auto renewed certificates. This has been removed from the spec and is not supported in Boulder.
|
||||
|
||||
### Fixed:
|
||||
- lib: Fix a problem with the Route53 provider where it was possible the verification was published to a private zone.
|
||||
- lib: Loading an account from file should fail if a integral part is nil
|
||||
- lib: Fix a potential issue where the Dyn provider could resolve to an incorrect zone.
|
||||
- lib: If a registration encounteres a conflict, the old registration is now recovered.
|
||||
- CLI: The account.json file no longer has the executable flag set.
|
||||
- lib: Made the client registration more robust in case of a 403 HTTP response.
|
||||
- lib: Fixed an issue with zone lookups when they have a CNAME in another zone.
|
||||
- lib: Fixed the lookup for the authoritative zone for Google Cloud.
|
||||
- lib: Fixed a race condition in the nonce store.
|
||||
- lib: The Google Cloud provider now removes old entries before trying to add new ones.
|
||||
- lib: Fixed a condition where we could stall due to an early error condition.
|
||||
- lib: Fixed an issue where Authz object could end up in an active state after an error condition.
|
||||
|
||||
## [0.3.1] - 2016-04-19
|
||||
|
||||
### Added:
|
||||
- lib: A new DNS provider for Vultr.
|
||||
|
||||
### Fixed:
|
||||
- lib: DNS Provider for DigitalOcean could not handle subdomains properly.
|
||||
- lib: handleHTTPError should only try to JSON decode error messages with the right content type.
|
||||
- lib: The propagation checker for the DNS challenge would not retry on send errors.
|
||||
|
||||
|
||||
## [0.3.0] - 2016-03-19
|
||||
|
||||
### Added:
|
||||
- CLI: The `--dns` switch. To include the DNS challenge for consideration. When using this switch, all other solvers are disabled. Supported are the following solvers: cloudflare, digitalocean, dnsimple, dyn, gandi, googlecloud, namecheap, route53, rfc2136 and manual.
|
||||
- CLI: The `--accept-tos` switch. Indicates your acceptance of the Let's Encrypt terms of service without prompting you.
|
||||
- CLI: The `--webroot` switch. The HTTP-01 challenge may now be completed by dropping a file into a webroot. When using this switch, all other solvers are disabled.
|
||||
- CLI: The `--key-type` switch. This replaces the `--rsa-key-size` switch and supports the following key types: EC256, EC384, RSA2048, RSA4096 and RSA8192.
|
||||
- CLI: The `--dnshelp` switch. This displays a more in-depth help topic for DNS solvers.
|
||||
- CLI: The `--no-bundle` sub switch for the `run` and `renew` commands. When this switch is set, the CLI will not bundle the issuer certificate with your certificate.
|
||||
- lib: A new type for challenge identifiers `Challenge`
|
||||
- lib: A new interface for custom challenge providers `acme.ChallengeProvider`
|
||||
- lib: A new interface for DNS-01 providers to allow for custom timeouts for the validation function `acme.ChallengeProviderTimeout`
|
||||
- lib: SetChallengeProvider function. Pass a challenge identifier and a Provider to replace the default behaviour of a challenge.
|
||||
- lib: The DNS-01 challenge has been implemented with modular solvers using the `ChallengeProvider` interface. Included solvers are: cloudflare, digitalocean, dnsimple, gandi, namecheap, route53, rfc2136 and manual.
|
||||
- lib: The `acme.KeyType` type was added and is used for the configuration of crypto parameters for RSA and EC keys. Valid KeyTypes are: EC256, EC384, RSA2048, RSA4096 and RSA8192.
|
||||
|
||||
### Changed
|
||||
- lib: ExcludeChallenges now expects to be passed an array of `Challenge` types.
|
||||
- lib: HTTP-01 now supports custom solvers using the `ChallengeProvider` interface.
|
||||
- lib: TLS-SNI-01 now supports custom solvers using the `ChallengeProvider` interface.
|
||||
- lib: The `GetPrivateKey` function in the `acme.User` interface is now expected to return a `crypto.PrivateKey` instead of an `rsa.PrivateKey` for EC compat.
|
||||
- lib: The `acme.NewClient` function now expects an `acme.KeyType` instead of the keyBits parameter.
|
||||
|
||||
### Removed
|
||||
- CLI: The `rsa-key-size` switch was removed in favor of `key-type` to support EC keys.
|
||||
|
||||
### Fixed
|
||||
- lib: Fixed a race condition in HTTP-01
|
||||
- lib: Fixed an issue where status codes on ACME challenge responses could lead to no action being taken.
|
||||
- lib: Fixed a regression when calling the Renew function with a SAN certificate.
|
||||
|
||||
## [0.2.0] - 2016-01-09
|
||||
|
||||
### Added:
|
||||
- CLI: The `--exclude` or `-x` switch. To exclude a challenge from being solved.
|
||||
- CLI: The `--http` switch. To set the listen address and port of HTTP based challenges. Supports `host:port` and `:port` for any interface.
|
||||
- CLI: The `--tls` switch. To set the listen address and port of TLS based challenges. Supports `host:port` and `:port` for any interface.
|
||||
- CLI: The `--reuse-key` switch for the `renew` operation. This lets you reuse an existing private key for renewals.
|
||||
- lib: ExcludeChallenges function. Pass an array of challenge identifiers to exclude them from solving.
|
||||
- lib: SetHTTPAddress function. Pass a port to set the listen port for HTTP based challenges.
|
||||
- lib: SetTLSAddress function. Pass a port to set the listen port of TLS based challenges.
|
||||
- lib: acme.UserAgent variable. Use this to customize the user agent on all requests sent by lego.
|
||||
|
||||
### Changed:
|
||||
- lib: NewClient does no longer accept the optPort parameter
|
||||
- lib: ObtainCertificate now returns a SAN certificate if you pass more then one domain.
|
||||
- lib: GetOCSPForCert now returns the parsed OCSP response instead of just the status.
|
||||
- lib: ObtainCertificate has a new parameter `privKey crypto.PrivateKey` which lets you reuse an existing private key for new certificates.
|
||||
- lib: RenewCertificate now expects the PrivateKey property of the CertificateResource to be set only if you want to reuse the key.
|
||||
|
||||
### Removed:
|
||||
- CLI: The `--port` switch was removed.
|
||||
- lib: RenewCertificate does no longer offer to also revoke your old certificate.
|
||||
|
||||
### Fixed:
|
||||
- CLI: Fix logic using the `--days` parameter for renew
|
||||
|
||||
## [0.1.1] - 2015-12-18
|
||||
|
||||
### Added:
|
||||
- CLI: Added a way to automate renewal through a cronjob using the --days parameter to renew
|
||||
|
||||
### Changed:
|
||||
- lib: Improved log output on challenge failures.
|
||||
|
||||
### Fixed:
|
||||
- CLI: The short parameter for domains would not get accepted
|
||||
- CLI: The cli did not return proper exit codes on error library errors.
|
||||
- lib: RenewCertificate did not properly renew SAN certificates.
|
||||
|
||||
### Security
|
||||
- lib: Fix possible DOS on GetOCSPForCert
|
||||
|
||||
## [0.1.0] - 2015-12-03
|
||||
- Initial release
|
||||
|
||||
[0.3.1]: https://github.com/go-acme/lego/compare/v0.3.0...v0.3.1
|
||||
[0.3.0]: https://github.com/go-acme/lego/compare/v0.2.0...v0.3.0
|
||||
[0.2.0]: https://github.com/go-acme/lego/compare/v0.1.1...v0.2.0
|
||||
[0.1.1]: https://github.com/go-acme/lego/compare/v0.1.0...v0.1.1
|
||||
[0.1.0]: https://github.com/go-acme/lego/tree/v0.1.0
|
80
CONTRIBUTING.md
Normal file
80
CONTRIBUTING.md
Normal file
|
@ -0,0 +1,80 @@
|
|||
# How to contribute to lego
|
||||
|
||||
Contributions in the form of patches and proposals are essential to keep lego great and to make it even better.
|
||||
To ensure a great and easy experience for everyone, please review the few guidelines in this document.
|
||||
|
||||
## Bug reports
|
||||
|
||||
- Use the issue search to see if the issue has already been reported.
|
||||
- Also look for closed issues to see if your issue has already been fixed.
|
||||
- If both of the above do not apply create a new issue and include as much information as possible.
|
||||
|
||||
Bug reports should include all information a person could need to reproduce your problem without the need to
|
||||
follow up for more information. If possible, provide detailed steps for us to reproduce it, the expected behaviour and the actual behaviour.
|
||||
|
||||
## Feature proposals and requests
|
||||
|
||||
Feature requests are welcome and should be discussed in an issue.
|
||||
Please keep proposals focused on one thing at a time and be as detailed as possible.
|
||||
It is up to you to make a strong point about your proposal and convince us of the merits and the added complexity of this feature.
|
||||
|
||||
## Pull requests
|
||||
|
||||
Patches, new features and improvements are a great way to help the project.
|
||||
Please keep them focused on one thing and do not include unrelated commits.
|
||||
|
||||
All pull requests which alter the behaviour of the program, add new behaviour or somehow alter code in a non-trivial way should **always** include tests.
|
||||
|
||||
If you want to contribute a significant pull request (with a non-trivial workload for you) please **ask first**. We do not want you to spend
|
||||
a lot of time on something the project's developers might not want to merge into the project.
|
||||
|
||||
**IMPORTANT**: By submitting a patch, you agree to allow the project
|
||||
owners to license your work under the terms of the [MIT License](LICENSE).
|
||||
|
||||
### How to create a pull request
|
||||
|
||||
Requirements:
|
||||
|
||||
- `go` v1.15+
|
||||
- environment variable: `GO111MODULE=on`
|
||||
|
||||
First, you have to install [GoLang](https://golang.org/doc/install) and [golangci-lint](https://github.com/golangci/golangci-lint#install).
|
||||
|
||||
```bash
|
||||
# Create the root folder
|
||||
mkdir -p $GOPATH/src/github.com/go-acme
|
||||
cd $GOPATH/src/github.com/go-acme
|
||||
|
||||
# clone your fork
|
||||
git clone git@github.com:YOUR_USERNAME/lego.git
|
||||
cd lego
|
||||
|
||||
# Add the go-acme/lego remote
|
||||
git remote add upstream git@github.com:go-acme/lego.git
|
||||
git fetch upstream
|
||||
```
|
||||
|
||||
```bash
|
||||
# Create your branch
|
||||
git checkout -b my-feature
|
||||
|
||||
## Create your code ##
|
||||
```
|
||||
|
||||
```bash
|
||||
# Format
|
||||
make fmt
|
||||
# Linters
|
||||
make checks
|
||||
# Tests
|
||||
make test
|
||||
# Compile
|
||||
make build
|
||||
```
|
||||
|
||||
```bash
|
||||
# push your branch
|
||||
git push -u origin my-feature
|
||||
|
||||
## create a pull request on GitHub ##
|
||||
```
|
24
Dockerfile
Normal file
24
Dockerfile
Normal file
|
@ -0,0 +1,24 @@
|
|||
FROM golang:1-alpine as builder
|
||||
|
||||
RUN apk --no-cache --no-progress add make git
|
||||
|
||||
WORKDIR /go/lego
|
||||
|
||||
ENV GO111MODULE on
|
||||
|
||||
# Download go modules
|
||||
COPY go.mod .
|
||||
COPY go.sum .
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN make build
|
||||
|
||||
FROM alpine:3
|
||||
RUN apk update \
|
||||
&& apk add --no-cache ca-certificates tzdata \
|
||||
&& update-ca-certificates
|
||||
|
||||
COPY --from=builder /go/lego/dist/lego /usr/bin/lego
|
||||
|
||||
ENTRYPOINT [ "/usr/bin/lego" ]
|
21
LICENSE
Normal file
21
LICENSE
Normal file
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2017 Sebastian Erhart
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
80
Makefile
Normal file
80
Makefile
Normal file
|
@ -0,0 +1,80 @@
|
|||
.PHONY: clean checks test build image e2e fmt
|
||||
|
||||
export GO111MODULE=on
|
||||
export CGO_ENABLED=0
|
||||
|
||||
LEGO_IMAGE := goacme/lego
|
||||
MAIN_DIRECTORY := ./cmd/lego/
|
||||
|
||||
BIN_OUTPUT := $(if $(filter $(shell go env GOOS), windows), dist/lego.exe, dist/lego)
|
||||
|
||||
TAG_NAME := $(shell git tag -l --contains HEAD)
|
||||
SHA := $(shell git rev-parse HEAD)
|
||||
VERSION := $(if $(TAG_NAME),$(TAG_NAME),$(SHA))
|
||||
|
||||
default: clean generate-dns checks test build
|
||||
|
||||
clean:
|
||||
@echo BIN_OUTPUT: ${BIN_OUTPUT}
|
||||
rm -rf dist/ builds/ cover.out
|
||||
|
||||
build: clean
|
||||
@echo Version: $(VERSION)
|
||||
go build -trimpath -ldflags '-X "main.version=${VERSION}"' -o ${BIN_OUTPUT} ${MAIN_DIRECTORY}
|
||||
|
||||
image:
|
||||
@echo Version: $(VERSION)
|
||||
docker build -t $(LEGO_IMAGE) .
|
||||
|
||||
test: clean
|
||||
go test -v -cover ./...
|
||||
|
||||
e2e: clean
|
||||
LEGO_E2E_TESTS=local go test -count=1 -v ./e2e/...
|
||||
|
||||
checks:
|
||||
golangci-lint run
|
||||
|
||||
# Release helper
|
||||
.PHONY: patch minor major detach
|
||||
|
||||
patch:
|
||||
go run internal/release.go release -m patch
|
||||
|
||||
minor:
|
||||
go run internal/release.go release -m minor
|
||||
|
||||
major:
|
||||
go run internal/release.go release -m major
|
||||
|
||||
detach:
|
||||
go run internal/release.go detach
|
||||
|
||||
# Docs
|
||||
.PHONY: docs-build docs-serve docs-themes
|
||||
|
||||
docs-build: generate-dns
|
||||
@make -C ./docs hugo-build
|
||||
|
||||
docs-serve: generate-dns
|
||||
@make -C ./docs hugo
|
||||
|
||||
docs-themes:
|
||||
@make -C ./docs hugo-themes
|
||||
|
||||
# DNS Documentation
|
||||
.PHONY: generate-dns validate-doc
|
||||
|
||||
generate-dns:
|
||||
go generate ./...
|
||||
|
||||
validate-doc: generate-dns
|
||||
validate-doc: DOC_DIRECTORIES := ./docs/ ./cmd/
|
||||
validate-doc:
|
||||
@if git diff --exit-code --quiet $(DOC_DIRECTORIES) 2>/dev/null; then \
|
||||
echo 'All documentation changes are done the right way.'; \
|
||||
else \
|
||||
echo 'The documentation must be regenerated, please use `make generate-dns`.'; \
|
||||
git status --porcelain -- $(DOC_DIRECTORIES) 2>/dev/null; \
|
||||
exit 2; \
|
||||
fi
|
90
README.md
Normal file
90
README.md
Normal file
|
@ -0,0 +1,90 @@
|
|||
<div align="center">
|
||||
<img alt="lego logo" src="./docs/static/images/lego-logo.min.svg">
|
||||
<p>Automatic Certificates and HTTPS for everyone.</p>
|
||||
</div>
|
||||
|
||||
# Lego
|
||||
|
||||
Let's Encrypt client and ACME library written in Go.
|
||||
|
||||
[![Go Reference](https://pkg.go.dev/badge/github.com/go-acme/lego/v4.svg)](https://pkg.go.dev/github.com/go-acme/lego/v4)
|
||||
[![Build Status](https://github.com//go-acme/lego/workflows/Main/badge.svg?branch=master)](https://github.com//go-acme/lego/actions)
|
||||
[![Docker Pulls](https://img.shields.io/docker/pulls/goacme/lego.svg)](https://hub.docker.com/r/goacme/lego/)
|
||||
|
||||
## Features
|
||||
|
||||
- ACME v2 [RFC 8555](https://www.rfc-editor.org/rfc/rfc8555.html)
|
||||
- Support [RFC 8737](https://www.rfc-editor.org/rfc/rfc8737.html): TLS Application‑Layer Protocol Negotiation (ALPN) Challenge Extension
|
||||
- Support [RFC 8738](https://www.rfc-editor.org/rfc/rfc8738.html): certificates for IP addresses
|
||||
- Support [draft-ietf-acme-ari-01](https://datatracker.ietf.org/doc/draft-ietf-acme-ari/): Renewal Information (ARI) Extension
|
||||
- Register with CA
|
||||
- Obtain certificates, both from scratch or with an existing CSR
|
||||
- Renew certificates
|
||||
- Revoke certificates
|
||||
- Robust implementation of all ACME challenges
|
||||
- HTTP (http-01)
|
||||
- DNS (dns-01)
|
||||
- TLS (tls-alpn-01)
|
||||
- SAN certificate support
|
||||
- [CNAME support](https://letsencrypt.org/2019/10/09/onboarding-your-customers-with-lets-encrypt-and-acme.html) by default
|
||||
- Comes with multiple optional [DNS providers](https://go-acme.github.io/lego/dns)
|
||||
- [Custom challenge solvers](https://go-acme.github.io/lego/usage/library/writing-a-challenge-solver/)
|
||||
- Certificate bundling
|
||||
- OCSP helper function
|
||||
|
||||
## Installation
|
||||
|
||||
How to [install](https://go-acme.github.io/lego/installation/).
|
||||
|
||||
## Usage
|
||||
|
||||
- as a [CLI](https://go-acme.github.io/lego/usage/cli)
|
||||
- as a [library](https://go-acme.github.io/lego/usage/library)
|
||||
|
||||
## Documentation
|
||||
|
||||
Documentation is hosted live at https://go-acme.github.io/lego/.
|
||||
|
||||
## DNS providers
|
||||
|
||||
Detailed documentation is available [here](https://go-acme.github.io/lego/dns).
|
||||
|
||||
<!-- START DNS PROVIDERS LIST -->
|
||||
|
||||
| | | | |
|
||||
|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
|
||||
| [Akamai EdgeDNS](https://go-acme.github.io/lego/dns/edgedns/) | [Alibaba Cloud DNS](https://go-acme.github.io/lego/dns/alidns/) | [all-inkl](https://go-acme.github.io/lego/dns/allinkl/) | [Amazon Lightsail](https://go-acme.github.io/lego/dns/lightsail/) |
|
||||
| [Amazon Route 53](https://go-acme.github.io/lego/dns/route53/) | [ArvanCloud](https://go-acme.github.io/lego/dns/arvancloud/) | [Aurora DNS](https://go-acme.github.io/lego/dns/auroradns/) | [Autodns](https://go-acme.github.io/lego/dns/autodns/) |
|
||||
| [Azure (deprecated)](https://go-acme.github.io/lego/dns/azure/) | [AzureDNS](https://go-acme.github.io/lego/dns/azuredns/) | [Bindman](https://go-acme.github.io/lego/dns/bindman/) | [Bluecat](https://go-acme.github.io/lego/dns/bluecat/) |
|
||||
| [Brandit](https://go-acme.github.io/lego/dns/brandit/) | [Bunny](https://go-acme.github.io/lego/dns/bunny/) | [Checkdomain](https://go-acme.github.io/lego/dns/checkdomain/) | [Civo](https://go-acme.github.io/lego/dns/civo/) |
|
||||
| [CloudDNS](https://go-acme.github.io/lego/dns/clouddns/) | [Cloudflare](https://go-acme.github.io/lego/dns/cloudflare/) | [ClouDNS](https://go-acme.github.io/lego/dns/cloudns/) | [CloudXNS](https://go-acme.github.io/lego/dns/cloudxns/) |
|
||||
| [ConoHa](https://go-acme.github.io/lego/dns/conoha/) | [Constellix](https://go-acme.github.io/lego/dns/constellix/) | [Derak Cloud](https://go-acme.github.io/lego/dns/derak/) | [deSEC.io](https://go-acme.github.io/lego/dns/desec/) |
|
||||
| [Designate DNSaaS for Openstack](https://go-acme.github.io/lego/dns/designate/) | [Digital Ocean](https://go-acme.github.io/lego/dns/digitalocean/) | [DNS Made Easy](https://go-acme.github.io/lego/dns/dnsmadeeasy/) | [dnsHome.de](https://go-acme.github.io/lego/dns/dnshomede/) |
|
||||
| [DNSimple](https://go-acme.github.io/lego/dns/dnsimple/) | [DNSPod (deprecated)](https://go-acme.github.io/lego/dns/dnspod/) | [Domain Offensive (do.de)](https://go-acme.github.io/lego/dns/dode/) | [Domeneshop](https://go-acme.github.io/lego/dns/domeneshop/) |
|
||||
| [DreamHost](https://go-acme.github.io/lego/dns/dreamhost/) | [Duck DNS](https://go-acme.github.io/lego/dns/duckdns/) | [Dyn](https://go-acme.github.io/lego/dns/dyn/) | [Dynu](https://go-acme.github.io/lego/dns/dynu/) |
|
||||
| [EasyDNS](https://go-acme.github.io/lego/dns/easydns/) | [Efficient IP](https://go-acme.github.io/lego/dns/efficientip/) | [Epik](https://go-acme.github.io/lego/dns/epik/) | [Exoscale](https://go-acme.github.io/lego/dns/exoscale/) |
|
||||
| [External program](https://go-acme.github.io/lego/dns/exec/) | [freemyip.com](https://go-acme.github.io/lego/dns/freemyip/) | [G-Core](https://go-acme.github.io/lego/dns/gcore/) | [Gandi Live DNS (v5)](https://go-acme.github.io/lego/dns/gandiv5/) |
|
||||
| [Gandi](https://go-acme.github.io/lego/dns/gandi/) | [Glesys](https://go-acme.github.io/lego/dns/glesys/) | [Go Daddy](https://go-acme.github.io/lego/dns/godaddy/) | [Google Cloud](https://go-acme.github.io/lego/dns/gcloud/) |
|
||||
| [Google Domains](https://go-acme.github.io/lego/dns/googledomains/) | [Hetzner](https://go-acme.github.io/lego/dns/hetzner/) | [Hosting.de](https://go-acme.github.io/lego/dns/hostingde/) | [Hosttech](https://go-acme.github.io/lego/dns/hosttech/) |
|
||||
| [HTTP request](https://go-acme.github.io/lego/dns/httpreq/) | [Hurricane Electric DNS](https://go-acme.github.io/lego/dns/hurricane/) | [HyperOne](https://go-acme.github.io/lego/dns/hyperone/) | [IBM Cloud (SoftLayer)](https://go-acme.github.io/lego/dns/ibmcloud/) |
|
||||
| [IIJ DNS Platform Service](https://go-acme.github.io/lego/dns/iijdpf/) | [Infoblox](https://go-acme.github.io/lego/dns/infoblox/) | [Infomaniak](https://go-acme.github.io/lego/dns/infomaniak/) | [Internet Initiative Japan](https://go-acme.github.io/lego/dns/iij/) |
|
||||
| [Internet.bs](https://go-acme.github.io/lego/dns/internetbs/) | [INWX](https://go-acme.github.io/lego/dns/inwx/) | [Ionos](https://go-acme.github.io/lego/dns/ionos/) | [IPv64](https://go-acme.github.io/lego/dns/ipv64/) |
|
||||
| [iwantmyname](https://go-acme.github.io/lego/dns/iwantmyname/) | [Joker](https://go-acme.github.io/lego/dns/joker/) | [Joohoi's ACME-DNS](https://go-acme.github.io/lego/dns/acme-dns/) | [Liara](https://go-acme.github.io/lego/dns/liara/) |
|
||||
| [Linode (v4)](https://go-acme.github.io/lego/dns/linode/) | [Liquid Web](https://go-acme.github.io/lego/dns/liquidweb/) | [Loopia](https://go-acme.github.io/lego/dns/loopia/) | [LuaDNS](https://go-acme.github.io/lego/dns/luadns/) |
|
||||
| [Manual](https://go-acme.github.io/lego/dns/manual/) | [Metaname](https://go-acme.github.io/lego/dns/metaname/) | [MyDNS.jp](https://go-acme.github.io/lego/dns/mydnsjp/) | [MythicBeasts](https://go-acme.github.io/lego/dns/mythicbeasts/) |
|
||||
| [Name.com](https://go-acme.github.io/lego/dns/namedotcom/) | [Namecheap](https://go-acme.github.io/lego/dns/namecheap/) | [Namesilo](https://go-acme.github.io/lego/dns/namesilo/) | [NearlyFreeSpeech.NET](https://go-acme.github.io/lego/dns/nearlyfreespeech/) |
|
||||
| [Netcup](https://go-acme.github.io/lego/dns/netcup/) | [Netlify](https://go-acme.github.io/lego/dns/netlify/) | [Nicmanager](https://go-acme.github.io/lego/dns/nicmanager/) | [NIFCloud](https://go-acme.github.io/lego/dns/nifcloud/) |
|
||||
| [Njalla](https://go-acme.github.io/lego/dns/njalla/) | [Nodion](https://go-acme.github.io/lego/dns/nodion/) | [NS1](https://go-acme.github.io/lego/dns/ns1/) | [Open Telekom Cloud](https://go-acme.github.io/lego/dns/otc/) |
|
||||
| [Oracle Cloud](https://go-acme.github.io/lego/dns/oraclecloud/) | [OVH](https://go-acme.github.io/lego/dns/ovh/) | [plesk.com](https://go-acme.github.io/lego/dns/plesk/) | [Porkbun](https://go-acme.github.io/lego/dns/porkbun/) |
|
||||
| [PowerDNS](https://go-acme.github.io/lego/dns/pdns/) | [Rackspace](https://go-acme.github.io/lego/dns/rackspace/) | [RcodeZero](https://go-acme.github.io/lego/dns/rcodezero/) | [reg.ru](https://go-acme.github.io/lego/dns/regru/) |
|
||||
| [RFC2136](https://go-acme.github.io/lego/dns/rfc2136/) | [RimuHosting](https://go-acme.github.io/lego/dns/rimuhosting/) | [Sakura Cloud](https://go-acme.github.io/lego/dns/sakuracloud/) | [Scaleway](https://go-acme.github.io/lego/dns/scaleway/) |
|
||||
| [Selectel](https://go-acme.github.io/lego/dns/selectel/) | [Servercow](https://go-acme.github.io/lego/dns/servercow/) | [Simply.com](https://go-acme.github.io/lego/dns/simply/) | [Sonic](https://go-acme.github.io/lego/dns/sonic/) |
|
||||
| [Stackpath](https://go-acme.github.io/lego/dns/stackpath/) | [Tencent Cloud DNS](https://go-acme.github.io/lego/dns/tencentcloud/) | [TransIP](https://go-acme.github.io/lego/dns/transip/) | [UKFast SafeDNS](https://go-acme.github.io/lego/dns/safedns/) |
|
||||
| [Ultradns](https://go-acme.github.io/lego/dns/ultradns/) | [Variomedia](https://go-acme.github.io/lego/dns/variomedia/) | [VegaDNS](https://go-acme.github.io/lego/dns/vegadns/) | [Vercel](https://go-acme.github.io/lego/dns/vercel/) |
|
||||
| [Versio.[nl/eu/uk]](https://go-acme.github.io/lego/dns/versio/) | [VinylDNS](https://go-acme.github.io/lego/dns/vinyldns/) | [VK Cloud](https://go-acme.github.io/lego/dns/vkcloud/) | [Vscale](https://go-acme.github.io/lego/dns/vscale/) |
|
||||
| [Vultr](https://go-acme.github.io/lego/dns/vultr/) | [Websupport](https://go-acme.github.io/lego/dns/websupport/) | [WEDOS](https://go-acme.github.io/lego/dns/wedos/) | [Yandex Cloud](https://go-acme.github.io/lego/dns/yandexcloud/) |
|
||||
| [Yandex PDD](https://go-acme.github.io/lego/dns/yandex/) | [Zone.ee](https://go-acme.github.io/lego/dns/zoneee/) | [Zonomi](https://go-acme.github.io/lego/dns/zonomi/) | |
|
||||
|
||||
<!-- END DNS PROVIDERS LIST -->
|
||||
|
||||
If your DNS provider is not supported, please open an [issue](https://github.com/go-acme/lego/issues/new?assignees=&labels=enhancement%2C+new-provider&template=new_dns_provider.md).
|
85
acme/api/account.go
Normal file
85
acme/api/account.go
Normal file
|
@ -0,0 +1,85 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
type AccountService service
|
||||
|
||||
// New Creates a new account.
|
||||
func (a *AccountService) New(req acme.Account) (acme.ExtendedAccount, error) {
|
||||
var account acme.Account
|
||||
resp, err := a.core.post(a.core.GetDirectory().NewAccountURL, req, &account)
|
||||
location := getLocation(resp)
|
||||
|
||||
if len(location) > 0 {
|
||||
a.core.jws.SetKid(location)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return acme.ExtendedAccount{Location: location}, err
|
||||
}
|
||||
|
||||
return acme.ExtendedAccount{Account: account, Location: location}, nil
|
||||
}
|
||||
|
||||
// NewEAB Creates a new account with an External Account Binding.
|
||||
func (a *AccountService) NewEAB(accMsg acme.Account, kid, hmacEncoded string) (acme.ExtendedAccount, error) {
|
||||
hmac, err := base64.RawURLEncoding.DecodeString(hmacEncoded)
|
||||
if err != nil {
|
||||
return acme.ExtendedAccount{}, fmt.Errorf("acme: could not decode hmac key: %w", err)
|
||||
}
|
||||
|
||||
eabJWS, err := a.core.signEABContent(a.core.GetDirectory().NewAccountURL, kid, hmac)
|
||||
if err != nil {
|
||||
return acme.ExtendedAccount{}, fmt.Errorf("acme: error signing eab content: %w", err)
|
||||
}
|
||||
|
||||
accMsg.ExternalAccountBinding = eabJWS
|
||||
|
||||
return a.New(accMsg)
|
||||
}
|
||||
|
||||
// Get Retrieves an account.
|
||||
func (a *AccountService) Get(accountURL string) (acme.Account, error) {
|
||||
if accountURL == "" {
|
||||
return acme.Account{}, errors.New("account[get]: empty URL")
|
||||
}
|
||||
|
||||
var account acme.Account
|
||||
_, err := a.core.postAsGet(accountURL, &account)
|
||||
if err != nil {
|
||||
return acme.Account{}, err
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
// Update Updates an account.
|
||||
func (a *AccountService) Update(accountURL string, req acme.Account) (acme.Account, error) {
|
||||
if accountURL == "" {
|
||||
return acme.Account{}, errors.New("account[update]: empty URL")
|
||||
}
|
||||
|
||||
var account acme.Account
|
||||
_, err := a.core.post(accountURL, req, &account)
|
||||
if err != nil {
|
||||
return acme.Account{}, err
|
||||
}
|
||||
|
||||
return account, nil
|
||||
}
|
||||
|
||||
// Deactivate Deactivates an account.
|
||||
func (a *AccountService) Deactivate(accountURL string) error {
|
||||
if accountURL == "" {
|
||||
return errors.New("account[deactivate]: empty URL")
|
||||
}
|
||||
|
||||
req := acme.Account{Status: acme.StatusDeactivated}
|
||||
_, err := a.core.post(accountURL, req, nil)
|
||||
return err
|
||||
}
|
165
acme/api/api.go
Normal file
165
acme/api/api.go
Normal file
|
@ -0,0 +1,165 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/cenkalti/backoff/v4"
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/nonces"
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/secure"
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/sender"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
// Core ACME/LE core API.
|
||||
type Core struct {
|
||||
doer *sender.Doer
|
||||
nonceManager *nonces.Manager
|
||||
jws *secure.JWS
|
||||
directory acme.Directory
|
||||
HTTPClient *http.Client
|
||||
|
||||
common service // Reuse a single struct instead of allocating one for each service on the heap.
|
||||
Accounts *AccountService
|
||||
Authorizations *AuthorizationService
|
||||
Certificates *CertificateService
|
||||
Challenges *ChallengeService
|
||||
Orders *OrderService
|
||||
}
|
||||
|
||||
// New Creates a new Core.
|
||||
func New(httpClient *http.Client, userAgent, caDirURL, kid string, privateKey crypto.PrivateKey) (*Core, error) {
|
||||
doer := sender.NewDoer(httpClient, userAgent)
|
||||
|
||||
dir, err := getDirectory(doer, caDirURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
nonceManager := nonces.NewManager(doer, dir.NewNonceURL)
|
||||
|
||||
jws := secure.NewJWS(privateKey, kid, nonceManager)
|
||||
|
||||
c := &Core{doer: doer, nonceManager: nonceManager, jws: jws, directory: dir, HTTPClient: httpClient}
|
||||
|
||||
c.common.core = c
|
||||
c.Accounts = (*AccountService)(&c.common)
|
||||
c.Authorizations = (*AuthorizationService)(&c.common)
|
||||
c.Certificates = (*CertificateService)(&c.common)
|
||||
c.Challenges = (*ChallengeService)(&c.common)
|
||||
c.Orders = (*OrderService)(&c.common)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// post performs an HTTP POST request and parses the response body as JSON,
|
||||
// into the provided respBody object.
|
||||
func (a *Core) post(uri string, reqBody, response interface{}) (*http.Response, error) {
|
||||
content, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to marshal message")
|
||||
}
|
||||
|
||||
return a.retrievablePost(uri, content, response)
|
||||
}
|
||||
|
||||
// postAsGet performs an HTTP POST ("POST-as-GET") request.
|
||||
// https://www.rfc-editor.org/rfc/rfc8555.html#section-6.3
|
||||
func (a *Core) postAsGet(uri string, response interface{}) (*http.Response, error) {
|
||||
return a.retrievablePost(uri, []byte{}, response)
|
||||
}
|
||||
|
||||
func (a *Core) retrievablePost(uri string, content []byte, response interface{}) (*http.Response, error) {
|
||||
// during tests, allow to support ~90% of bad nonce with a minimum of attempts.
|
||||
bo := backoff.NewExponentialBackOff()
|
||||
bo.InitialInterval = 200 * time.Millisecond
|
||||
bo.MaxInterval = 5 * time.Second
|
||||
bo.MaxElapsedTime = 20 * time.Second
|
||||
|
||||
var resp *http.Response
|
||||
operation := func() error {
|
||||
var err error
|
||||
resp, err = a.signedPost(uri, content, response)
|
||||
if err != nil {
|
||||
// Retry if the nonce was invalidated
|
||||
var e *acme.NonceError
|
||||
if errors.As(err, &e) {
|
||||
return err
|
||||
}
|
||||
|
||||
return backoff.Permanent(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
notify := func(err error, duration time.Duration) {
|
||||
log.Infof("retry due to: %v", err)
|
||||
}
|
||||
|
||||
err := backoff.RetryNotify(operation, bo, notify)
|
||||
if err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (a *Core) signedPost(uri string, content []byte, response interface{}) (*http.Response, error) {
|
||||
signedContent, err := a.jws.SignContent(uri, content)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to post JWS message: failed to sign content: %w", err)
|
||||
}
|
||||
|
||||
signedBody := bytes.NewBufferString(signedContent.FullSerialize())
|
||||
|
||||
resp, err := a.doer.Post(uri, signedBody, "application/jose+json", response)
|
||||
|
||||
// nonceErr is ignored to keep the root error.
|
||||
nonce, nonceErr := nonces.GetFromResponse(resp)
|
||||
if nonceErr == nil {
|
||||
a.nonceManager.Push(nonce)
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (a *Core) signEABContent(newAccountURL, kid string, hmac []byte) ([]byte, error) {
|
||||
eabJWS, err := a.jws.SignEABContent(newAccountURL, kid, hmac)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return []byte(eabJWS.FullSerialize()), nil
|
||||
}
|
||||
|
||||
// GetKeyAuthorization Gets the key authorization.
|
||||
func (a *Core) GetKeyAuthorization(token string) (string, error) {
|
||||
return a.jws.GetKeyAuthorization(token)
|
||||
}
|
||||
|
||||
func (a *Core) GetDirectory() acme.Directory {
|
||||
return a.directory
|
||||
}
|
||||
|
||||
func getDirectory(do *sender.Doer, caDirURL string) (acme.Directory, error) {
|
||||
var dir acme.Directory
|
||||
if _, err := do.Get(caDirURL, &dir); err != nil {
|
||||
return dir, fmt.Errorf("get directory at '%s': %w", caDirURL, err)
|
||||
}
|
||||
|
||||
if dir.NewAccountURL == "" {
|
||||
return dir, errors.New("directory missing new registration URL")
|
||||
}
|
||||
if dir.NewOrderURL == "" {
|
||||
return dir, errors.New("directory missing new order URL")
|
||||
}
|
||||
|
||||
return dir, nil
|
||||
}
|
34
acme/api/authorization.go
Normal file
34
acme/api/authorization.go
Normal file
|
@ -0,0 +1,34 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
type AuthorizationService service
|
||||
|
||||
// Get Gets an authorization.
|
||||
func (c *AuthorizationService) Get(authzURL string) (acme.Authorization, error) {
|
||||
if authzURL == "" {
|
||||
return acme.Authorization{}, errors.New("authorization[get]: empty URL")
|
||||
}
|
||||
|
||||
var authz acme.Authorization
|
||||
_, err := c.core.postAsGet(authzURL, &authz)
|
||||
if err != nil {
|
||||
return acme.Authorization{}, err
|
||||
}
|
||||
return authz, nil
|
||||
}
|
||||
|
||||
// Deactivate Deactivates an authorization.
|
||||
func (c *AuthorizationService) Deactivate(authzURL string) error {
|
||||
if authzURL == "" {
|
||||
return errors.New("authorization[deactivate]: empty URL")
|
||||
}
|
||||
|
||||
var disabledAuth acme.Authorization
|
||||
_, err := c.core.post(authzURL, acme.Authorization{Status: acme.StatusDeactivated}, &disabledAuth)
|
||||
return err
|
||||
}
|
138
acme/api/certificate.go
Normal file
138
acme/api/certificate.go
Normal file
|
@ -0,0 +1,138 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
// maxBodySize is the maximum size of body that we will read.
|
||||
const maxBodySize = 1024 * 1024
|
||||
|
||||
type CertificateService service
|
||||
|
||||
// Get Returns the certificate and the issuer certificate.
|
||||
// 'bundle' is only applied if the issuer is provided by the 'up' link.
|
||||
func (c *CertificateService) Get(certURL string, bundle bool) ([]byte, []byte, error) {
|
||||
cert, _, err := c.get(certURL, bundle)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return cert.Cert, cert.Issuer, nil
|
||||
}
|
||||
|
||||
// GetAll the certificates and the alternate certificates.
|
||||
// bundle' is only applied if the issuer is provided by the 'up' link.
|
||||
func (c *CertificateService) GetAll(certURL string, bundle bool) (map[string]*acme.RawCertificate, error) {
|
||||
cert, headers, err := c.get(certURL, bundle)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
certs := map[string]*acme.RawCertificate{certURL: cert}
|
||||
|
||||
// URLs of "alternate" link relation
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.4.2
|
||||
alts := getLinks(headers, "alternate")
|
||||
|
||||
for _, alt := range alts {
|
||||
altCert, _, err := c.get(alt, bundle)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
certs[alt] = altCert
|
||||
}
|
||||
|
||||
return certs, nil
|
||||
}
|
||||
|
||||
// Revoke Revokes a certificate.
|
||||
func (c *CertificateService) Revoke(req acme.RevokeCertMessage) error {
|
||||
_, err := c.core.post(c.core.GetDirectory().RevokeCertURL, req, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// get Returns the certificate and the "up" link.
|
||||
func (c *CertificateService) get(certURL string, bundle bool) (*acme.RawCertificate, http.Header, error) {
|
||||
if certURL == "" {
|
||||
return nil, nil, errors.New("certificate[get]: empty URL")
|
||||
}
|
||||
|
||||
resp, err := c.core.postAsGet(certURL, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize))
|
||||
if err != nil {
|
||||
return nil, resp.Header, err
|
||||
}
|
||||
|
||||
cert := c.getCertificateChain(data, resp.Header, bundle, certURL)
|
||||
|
||||
return cert, resp.Header, err
|
||||
}
|
||||
|
||||
// getCertificateChain Returns the certificate and the issuer certificate.
|
||||
func (c *CertificateService) getCertificateChain(cert []byte, headers http.Header, bundle bool, certURL string) *acme.RawCertificate {
|
||||
// Get issuerCert from bundled response from Let's Encrypt
|
||||
// See https://community.letsencrypt.org/t/acme-v2-no-up-link-in-response/64962
|
||||
_, issuer := pem.Decode(cert)
|
||||
if issuer != nil {
|
||||
// If bundle is false, we want to return a single certificate.
|
||||
// To do this, we remove the issuer cert(s) from the issued cert.
|
||||
if !bundle {
|
||||
cert = bytes.TrimSuffix(cert, issuer)
|
||||
}
|
||||
return &acme.RawCertificate{Cert: cert, Issuer: issuer}
|
||||
}
|
||||
|
||||
// The issuer certificate link may be supplied via an "up" link
|
||||
// in the response headers of a new certificate.
|
||||
// See https://www.rfc-editor.org/rfc/rfc8555.html#section-7.4.2
|
||||
up := getLink(headers, "up")
|
||||
|
||||
issuer, err := c.getIssuerFromLink(up)
|
||||
if err != nil {
|
||||
// If we fail to acquire the issuer cert, return the issued certificate - do not fail.
|
||||
log.Warnf("acme: Could not bundle issuer certificate [%s]: %v", certURL, err)
|
||||
} else if len(issuer) > 0 {
|
||||
// If bundle is true, we want to return a certificate bundle.
|
||||
// To do this, we append the issuer cert to the issued cert.
|
||||
if bundle {
|
||||
cert = append(cert, issuer...)
|
||||
}
|
||||
}
|
||||
|
||||
return &acme.RawCertificate{Cert: cert, Issuer: issuer}
|
||||
}
|
||||
|
||||
// getIssuerFromLink requests the issuer certificate.
|
||||
func (c *CertificateService) getIssuerFromLink(up string) ([]byte, error) {
|
||||
if up == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
log.Infof("acme: Requesting issuer cert from %s", up)
|
||||
|
||||
cert, _, err := c.get(up, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = x509.ParseCertificate(cert.Cert)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return certcrypto.PEMEncode(certcrypto.DERCertificateBytes(cert.Cert)), nil
|
||||
}
|
130
acme/api/certificate_test.go
Normal file
130
acme/api/certificate_test.go
Normal file
|
@ -0,0 +1,130 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/pem"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const certResponseMock = `-----BEGIN CERTIFICATE-----
|
||||
MIIDEDCCAfigAwIBAgIHPhckqW5fPDANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQD
|
||||
Ex1QZWJibGUgSW50ZXJtZWRpYXRlIENBIDM5NWU2MTAeFw0xODExMDcxNzQ2NTZa
|
||||
Fw0yMzExMDcxNzQ2NTZaMBMxETAPBgNVBAMTCGFjbWUud3RmMIIBIjANBgkqhkiG
|
||||
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwtLNKvZXD20XPUQCWYSK9rUSKxD9Eb0c9fag
|
||||
bxOxOkLRTgL8LH6yln+bxc3MrHDou4PpDUdeo2CyOQu3CKsTS5mrH3NXYHu0H7p5
|
||||
y3riOJTHnfkGKLT9LciGz7GkXd62nvNP57bOf5Sk4P2M+Qbxd0hPTSfu52740LSy
|
||||
144cnxe2P1aDYehrEp6nYCESuyD/CtUHTo0qwJmzIy163Sp3rSs15BuCPyhySnE3
|
||||
BJ8Ggv+qC6D5I1932DfSqyQJ79iq/HRm0Fn84am3KwvRlUfWxabmsUGARXoqCgnE
|
||||
zcbJVOZKewv0zlQJpfac+b+Imj6Lvt1TGjIz2mVyefYgLx8gwwIDAQABo1QwUjAO
|
||||
BgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG
|
||||
A1UdEwEB/wQCMAAwEwYDVR0RBAwwCoIIYWNtZS53dGYwDQYJKoZIhvcNAQELBQAD
|
||||
ggEBABB/0iYhmfPSQot5RaeeovQnsqYjI5ryQK2cwzW6qcTJfv8N6+p6XkqF1+W4
|
||||
jXZjrQP8MvgO9KNWlvx12vhINE6wubk88L+2piAi5uS2QejmZbXpyYB9s+oPqlk9
|
||||
IDvfdlVYOqvYAhSx7ggGi+j73mjZVtjAavP6dKuu475ZCeq+NIC15RpbbikWKtYE
|
||||
HBJ7BW8XQKx67iHGx8ygHTDLbREL80Bck3oUm7wIYGMoNijD6RBl25p4gYl9dzOd
|
||||
TqGl5hW/1P5hMbgEzHbr4O3BfWqU2g7tV36TASy3jbC3ONFRNNYrpEZ1AL3+cUri
|
||||
OPPkKtAKAbQkKbUIfsHpBZjKZMU=
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE
|
||||
AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw
|
||||
NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl
|
||||
NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT
|
||||
SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh
|
||||
0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen
|
||||
SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx
|
||||
HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt
|
||||
D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu
|
||||
mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD
|
||||
AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA
|
||||
upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm
|
||||
iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd
|
||||
QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ
|
||||
wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv
|
||||
rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2
|
||||
7R4IbHGnj0BJA2vMYC4hSw==
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
const issuerMock = `-----BEGIN CERTIFICATE-----
|
||||
MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE
|
||||
AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw
|
||||
NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl
|
||||
NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT
|
||||
SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh
|
||||
0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen
|
||||
SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx
|
||||
HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt
|
||||
D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu
|
||||
mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD
|
||||
AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA
|
||||
upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm
|
||||
iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd
|
||||
QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ
|
||||
wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv
|
||||
rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2
|
||||
7R4IbHGnj0BJA2vMYC4hSw==
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
func TestCertificateService_Get_issuerRelUp(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`)
|
||||
_, err := w.Write([]byte(certResponseMock))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
mux.HandleFunc("/issuer", func(w http.ResponseWriter, _ *http.Request) {
|
||||
p, _ := pem.Decode([]byte(issuerMock))
|
||||
_, err := w.Write(p.Bytes)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
cert, issuer, err := core.Certificates.Get(apiURL+"/certificate", true)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, certResponseMock, string(cert), "Certificate")
|
||||
assert.Equal(t, issuerMock, string(issuer), "IssuerCertificate")
|
||||
}
|
||||
|
||||
func TestCertificateService_Get_embeddedIssuer(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, err := w.Write([]byte(certResponseMock))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
cert, issuer, err := core.Certificates.Get(apiURL+"/certificate", true)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, certResponseMock, string(cert), "Certificate")
|
||||
assert.Equal(t, issuerMock, string(issuer), "IssuerCertificate")
|
||||
}
|
45
acme/api/challenge.go
Normal file
45
acme/api/challenge.go
Normal file
|
@ -0,0 +1,45 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
type ChallengeService service
|
||||
|
||||
// New Creates a challenge.
|
||||
func (c *ChallengeService) New(chlgURL string) (acme.ExtendedChallenge, error) {
|
||||
if chlgURL == "" {
|
||||
return acme.ExtendedChallenge{}, errors.New("challenge[new]: empty URL")
|
||||
}
|
||||
|
||||
// Challenge initiation is done by sending a JWS payload containing the trivial JSON object `{}`.
|
||||
// We use an empty struct instance as the postJSON payload here to achieve this result.
|
||||
var chlng acme.ExtendedChallenge
|
||||
resp, err := c.core.post(chlgURL, struct{}{}, &chlng)
|
||||
if err != nil {
|
||||
return acme.ExtendedChallenge{}, err
|
||||
}
|
||||
|
||||
chlng.AuthorizationURL = getLink(resp.Header, "up")
|
||||
chlng.RetryAfter = getRetryAfter(resp)
|
||||
return chlng, nil
|
||||
}
|
||||
|
||||
// Get Gets a challenge.
|
||||
func (c *ChallengeService) Get(chlgURL string) (acme.ExtendedChallenge, error) {
|
||||
if chlgURL == "" {
|
||||
return acme.ExtendedChallenge{}, errors.New("challenge[get]: empty URL")
|
||||
}
|
||||
|
||||
var chlng acme.ExtendedChallenge
|
||||
resp, err := c.core.postAsGet(chlgURL, &chlng)
|
||||
if err != nil {
|
||||
return acme.ExtendedChallenge{}, err
|
||||
}
|
||||
|
||||
chlng.AuthorizationURL = getLink(resp.Header, "up")
|
||||
chlng.RetryAfter = getRetryAfter(resp)
|
||||
return chlng, nil
|
||||
}
|
78
acme/api/internal/nonces/nonce_manager.go
Normal file
78
acme/api/internal/nonces/nonce_manager.go
Normal file
|
@ -0,0 +1,78 @@
|
|||
package nonces
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/sender"
|
||||
)
|
||||
|
||||
// Manager Manages nonces.
|
||||
type Manager struct {
|
||||
do *sender.Doer
|
||||
nonceURL string
|
||||
nonces []string
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
// NewManager Creates a new Manager.
|
||||
func NewManager(do *sender.Doer, nonceURL string) *Manager {
|
||||
return &Manager{
|
||||
do: do,
|
||||
nonceURL: nonceURL,
|
||||
}
|
||||
}
|
||||
|
||||
// Pop Pops a nonce.
|
||||
func (n *Manager) Pop() (string, bool) {
|
||||
n.Lock()
|
||||
defer n.Unlock()
|
||||
|
||||
if len(n.nonces) == 0 {
|
||||
return "", false
|
||||
}
|
||||
|
||||
nonce := n.nonces[len(n.nonces)-1]
|
||||
n.nonces = n.nonces[:len(n.nonces)-1]
|
||||
return nonce, true
|
||||
}
|
||||
|
||||
// Push Pushes a nonce.
|
||||
func (n *Manager) Push(nonce string) {
|
||||
n.Lock()
|
||||
defer n.Unlock()
|
||||
n.nonces = append(n.nonces, nonce)
|
||||
}
|
||||
|
||||
// Nonce implement jose.NonceSource.
|
||||
func (n *Manager) Nonce() (string, error) {
|
||||
if nonce, ok := n.Pop(); ok {
|
||||
return nonce, nil
|
||||
}
|
||||
return n.getNonce()
|
||||
}
|
||||
|
||||
func (n *Manager) getNonce() (string, error) {
|
||||
resp, err := n.do.Head(n.nonceURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get nonce from HTTP HEAD: %w", err)
|
||||
}
|
||||
|
||||
return GetFromResponse(resp)
|
||||
}
|
||||
|
||||
// GetFromResponse Extracts a nonce from a HTTP response.
|
||||
func GetFromResponse(resp *http.Response) (string, error) {
|
||||
if resp == nil {
|
||||
return "", errors.New("nil response")
|
||||
}
|
||||
|
||||
nonce := resp.Header.Get("Replay-Nonce")
|
||||
if nonce == "" {
|
||||
return "", errors.New("server did not respond with a proper nonce header")
|
||||
}
|
||||
|
||||
return nonce, nil
|
||||
}
|
55
acme/api/internal/nonces/nonce_manager_test.go
Normal file
55
acme/api/internal/nonces/nonce_manager_test.go
Normal file
|
@ -0,0 +1,55 @@
|
|||
package nonces
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/sender"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
)
|
||||
|
||||
func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
w.Header().Set("Replay-Nonce", "12345")
|
||||
w.Header().Set("Retry-After", "0")
|
||||
err := tester.WriteJSONResponse(w, &acme.Challenge{Type: "http-01", Status: "Valid", URL: "http://example.com/", Token: "token"})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
doer := sender.NewDoer(http.DefaultClient, "lego-test")
|
||||
j := NewManager(doer, server.URL)
|
||||
ch := make(chan bool)
|
||||
resultCh := make(chan bool)
|
||||
go func() {
|
||||
_, errN := j.Nonce()
|
||||
if errN != nil {
|
||||
t.Log(errN)
|
||||
}
|
||||
ch <- true
|
||||
}()
|
||||
go func() {
|
||||
_, errN := j.Nonce()
|
||||
if errN != nil {
|
||||
t.Log(errN)
|
||||
}
|
||||
ch <- true
|
||||
}()
|
||||
go func() {
|
||||
<-ch
|
||||
<-ch
|
||||
resultCh <- true
|
||||
}()
|
||||
select {
|
||||
case <-resultCh:
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Fatal("JWS is probably holding a lock while making HTTP request")
|
||||
}
|
||||
}
|
130
acme/api/internal/secure/jws.go
Normal file
130
acme/api/internal/secure/jws.go
Normal file
|
@ -0,0 +1,130 @@
|
|||
package secure
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/nonces"
|
||||
jose "github.com/go-jose/go-jose/v3"
|
||||
)
|
||||
|
||||
// JWS Represents a JWS.
|
||||
type JWS struct {
|
||||
privKey crypto.PrivateKey
|
||||
kid string // Key identifier
|
||||
nonces *nonces.Manager
|
||||
}
|
||||
|
||||
// NewJWS Create a new JWS.
|
||||
func NewJWS(privateKey crypto.PrivateKey, kid string, nonceManager *nonces.Manager) *JWS {
|
||||
return &JWS{
|
||||
privKey: privateKey,
|
||||
nonces: nonceManager,
|
||||
kid: kid,
|
||||
}
|
||||
}
|
||||
|
||||
// SetKid Sets a key identifier.
|
||||
func (j *JWS) SetKid(kid string) {
|
||||
j.kid = kid
|
||||
}
|
||||
|
||||
// SignContent Signs a content with the JWS.
|
||||
func (j *JWS) SignContent(url string, content []byte) (*jose.JSONWebSignature, error) {
|
||||
var alg jose.SignatureAlgorithm
|
||||
switch k := j.privKey.(type) {
|
||||
case *rsa.PrivateKey:
|
||||
alg = jose.RS256
|
||||
case *ecdsa.PrivateKey:
|
||||
if k.Curve == elliptic.P256() {
|
||||
alg = jose.ES256
|
||||
} else if k.Curve == elliptic.P384() {
|
||||
alg = jose.ES384
|
||||
}
|
||||
}
|
||||
|
||||
signKey := jose.SigningKey{
|
||||
Algorithm: alg,
|
||||
Key: jose.JSONWebKey{Key: j.privKey, KeyID: j.kid},
|
||||
}
|
||||
|
||||
options := jose.SignerOptions{
|
||||
NonceSource: j.nonces,
|
||||
ExtraHeaders: map[jose.HeaderKey]interface{}{
|
||||
"url": url,
|
||||
},
|
||||
}
|
||||
|
||||
if j.kid == "" {
|
||||
options.EmbedJWK = true
|
||||
}
|
||||
|
||||
signer, err := jose.NewSigner(signKey, &options)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create jose signer: %w", err)
|
||||
}
|
||||
|
||||
signed, err := signer.Sign(content)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to sign content: %w", err)
|
||||
}
|
||||
return signed, nil
|
||||
}
|
||||
|
||||
// SignEABContent Signs an external account binding content with the JWS.
|
||||
func (j *JWS) SignEABContent(url, kid string, hmac []byte) (*jose.JSONWebSignature, error) {
|
||||
jwk := jose.JSONWebKey{Key: j.privKey}
|
||||
jwkJSON, err := jwk.Public().MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("acme: error encoding eab jwk key: %w", err)
|
||||
}
|
||||
|
||||
signer, err := jose.NewSigner(
|
||||
jose.SigningKey{Algorithm: jose.HS256, Key: hmac},
|
||||
&jose.SignerOptions{
|
||||
EmbedJWK: false,
|
||||
ExtraHeaders: map[jose.HeaderKey]interface{}{
|
||||
"kid": kid,
|
||||
"url": url,
|
||||
},
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create External Account Binding jose signer: %w", err)
|
||||
}
|
||||
|
||||
signed, err := signer.Sign(jwkJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to External Account Binding sign content: %w", err)
|
||||
}
|
||||
|
||||
return signed, nil
|
||||
}
|
||||
|
||||
// GetKeyAuthorization Gets the key authorization for a token.
|
||||
func (j *JWS) GetKeyAuthorization(token string) (string, error) {
|
||||
var publicKey crypto.PublicKey
|
||||
switch k := j.privKey.(type) {
|
||||
case *ecdsa.PrivateKey:
|
||||
publicKey = k.Public()
|
||||
case *rsa.PrivateKey:
|
||||
publicKey = k.Public()
|
||||
}
|
||||
|
||||
// Generate the Key Authorization for the challenge
|
||||
jwk := &jose.JSONWebKey{Key: publicKey}
|
||||
|
||||
thumbBytes, err := jwk.Thumbprint(crypto.SHA256)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// unpad the base64URL
|
||||
keyThumb := base64.RawURLEncoding.EncodeToString(thumbBytes)
|
||||
|
||||
return token + "." + keyThumb, nil
|
||||
}
|
56
acme/api/internal/secure/jws_test.go
Normal file
56
acme/api/internal/secure/jws_test.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package secure
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/nonces"
|
||||
"github.com/go-acme/lego/v4/acme/api/internal/sender"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
)
|
||||
|
||||
func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
w.Header().Set("Replay-Nonce", "12345")
|
||||
w.Header().Set("Retry-After", "0")
|
||||
err := tester.WriteJSONResponse(w, &acme.Challenge{Type: "http-01", Status: "Valid", URL: "http://example.com/", Token: "token"})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
doer := sender.NewDoer(http.DefaultClient, "lego-test")
|
||||
j := nonces.NewManager(doer, server.URL)
|
||||
ch := make(chan bool)
|
||||
resultCh := make(chan bool)
|
||||
go func() {
|
||||
_, errN := j.Nonce()
|
||||
if errN != nil {
|
||||
t.Log(errN)
|
||||
}
|
||||
ch <- true
|
||||
}()
|
||||
go func() {
|
||||
_, errN := j.Nonce()
|
||||
if errN != nil {
|
||||
t.Log(errN)
|
||||
}
|
||||
ch <- true
|
||||
}()
|
||||
go func() {
|
||||
<-ch
|
||||
<-ch
|
||||
resultCh <- true
|
||||
}()
|
||||
select {
|
||||
case <-resultCh:
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
t.Fatal("JWS is probably holding a lock while making HTTP request")
|
||||
}
|
||||
}
|
148
acme/api/internal/sender/sender.go
Normal file
148
acme/api/internal/sender/sender.go
Normal file
|
@ -0,0 +1,148 @@
|
|||
package sender
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
type RequestOption func(*http.Request) error
|
||||
|
||||
func contentType(ct string) RequestOption {
|
||||
return func(req *http.Request) error {
|
||||
req.Header.Set("Content-Type", ct)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type Doer struct {
|
||||
httpClient *http.Client
|
||||
userAgent string
|
||||
}
|
||||
|
||||
// NewDoer Creates a new Doer.
|
||||
func NewDoer(client *http.Client, userAgent string) *Doer {
|
||||
return &Doer{
|
||||
httpClient: client,
|
||||
userAgent: userAgent,
|
||||
}
|
||||
}
|
||||
|
||||
// Get performs a GET request with a proper User-Agent string.
|
||||
// If "response" is not provided, callers should close resp.Body when done reading from it.
|
||||
func (d *Doer) Get(url string, response interface{}) (*http.Response, error) {
|
||||
req, err := d.newRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d.do(req, response)
|
||||
}
|
||||
|
||||
// Head performs a HEAD request with a proper User-Agent string.
|
||||
// The response body (resp.Body) is already closed when this function returns.
|
||||
func (d *Doer) Head(url string) (*http.Response, error) {
|
||||
req, err := d.newRequest(http.MethodHead, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d.do(req, nil)
|
||||
}
|
||||
|
||||
// Post performs a POST request with a proper User-Agent string.
|
||||
// If "response" is not provided, callers should close resp.Body when done reading from it.
|
||||
func (d *Doer) Post(url string, body io.Reader, bodyType string, response interface{}) (*http.Response, error) {
|
||||
req, err := d.newRequest(http.MethodPost, url, body, contentType(bodyType))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return d.do(req, response)
|
||||
}
|
||||
|
||||
func (d *Doer) newRequest(method, uri string, body io.Reader, opts ...RequestOption) (*http.Request, error) {
|
||||
req, err := http.NewRequest(method, uri, body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", d.formatUserAgent())
|
||||
|
||||
for _, opt := range opts {
|
||||
err = opt(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func (d *Doer) do(req *http.Request, response interface{}) (*http.Response, error) {
|
||||
resp, err := d.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = checkError(req, resp); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if response != nil {
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
err = json.Unmarshal(raw, response)
|
||||
if err != nil {
|
||||
return resp, fmt.Errorf("failed to unmarshal %q to type %T: %w", raw, response, err)
|
||||
}
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// formatUserAgent builds and returns the User-Agent string to use in requests.
|
||||
func (d *Doer) formatUserAgent() string {
|
||||
ua := fmt.Sprintf("%s %s (%s; %s; %s)", d.userAgent, ourUserAgent, ourUserAgentComment, runtime.GOOS, runtime.GOARCH)
|
||||
return strings.TrimSpace(ua)
|
||||
}
|
||||
|
||||
func checkError(req *http.Request, resp *http.Response) error {
|
||||
if resp.StatusCode >= http.StatusBadRequest {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%d :: %s :: %s :: %w", resp.StatusCode, req.Method, req.URL, err)
|
||||
}
|
||||
|
||||
var errorDetails *acme.ProblemDetails
|
||||
err = json.Unmarshal(body, &errorDetails)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%d ::%s :: %s :: %w :: %s", resp.StatusCode, req.Method, req.URL, err, string(body))
|
||||
}
|
||||
|
||||
errorDetails.Method = req.Method
|
||||
errorDetails.URL = req.URL.String()
|
||||
|
||||
if errorDetails.HTTPStatus == 0 {
|
||||
errorDetails.HTTPStatus = resp.StatusCode
|
||||
}
|
||||
|
||||
// Check for errors we handle specifically
|
||||
if errorDetails.HTTPStatus == http.StatusBadRequest && errorDetails.Type == acme.BadNonceErr {
|
||||
return &acme.NonceError{ProblemDetails: errorDetails}
|
||||
}
|
||||
|
||||
return errorDetails
|
||||
}
|
||||
return nil
|
||||
}
|
67
acme/api/internal/sender/sender_test.go
Normal file
67
acme/api/internal/sender/sender_test.go
Normal file
|
@ -0,0 +1,67 @@
|
|||
package sender
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDo_UserAgentOnAllHTTPMethod(t *testing.T) {
|
||||
var ua, method string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
ua = r.Header.Get("User-Agent")
|
||||
method = r.Method
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
doer := NewDoer(http.DefaultClient, "")
|
||||
|
||||
testCases := []struct {
|
||||
method string
|
||||
call func(u string) (*http.Response, error)
|
||||
}{
|
||||
{
|
||||
method: http.MethodGet,
|
||||
call: func(u string) (*http.Response, error) {
|
||||
return doer.Get(u, nil)
|
||||
},
|
||||
},
|
||||
{
|
||||
method: http.MethodHead,
|
||||
call: doer.Head,
|
||||
},
|
||||
{
|
||||
method: http.MethodPost,
|
||||
call: func(u string) (*http.Response, error) {
|
||||
return doer.Post(u, strings.NewReader("falalalala"), "text/plain", nil)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.method, func(t *testing.T) {
|
||||
_, err := test.call(server.URL)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, test.method, method)
|
||||
assert.Contains(t, ua, ourUserAgent, "User-Agent")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDo_CustomUserAgent(t *testing.T) {
|
||||
customUA := "MyApp/1.2.3"
|
||||
doer := NewDoer(http.DefaultClient, customUA)
|
||||
|
||||
ua := doer.formatUserAgent()
|
||||
assert.Contains(t, ua, ourUserAgent)
|
||||
assert.Contains(t, ua, customUA)
|
||||
if strings.HasSuffix(ua, " ") {
|
||||
t.Errorf("UA should not have trailing spaces; got '%s'", ua)
|
||||
}
|
||||
assert.Len(t, strings.Split(ua, " "), 5)
|
||||
}
|
14
acme/api/internal/sender/useragent.go
Normal file
14
acme/api/internal/sender/useragent.go
Normal file
|
@ -0,0 +1,14 @@
|
|||
package sender
|
||||
|
||||
// CODE GENERATED AUTOMATICALLY
|
||||
// THIS FILE MUST NOT BE EDITED BY HAND
|
||||
|
||||
const (
|
||||
// ourUserAgent is the User-Agent of this underlying library package.
|
||||
ourUserAgent = "xenolf-acme/4.13.2"
|
||||
|
||||
// ourUserAgentComment is part of the UA comment linked to the version status of this underlying library package.
|
||||
// values: detach|release
|
||||
// NOTE: Update this with each tagged release.
|
||||
ourUserAgentComment = "detach"
|
||||
)
|
94
acme/api/order.go
Normal file
94
acme/api/order.go
Normal file
|
@ -0,0 +1,94 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
// OrderOptions used to create an order (optional).
|
||||
type OrderOptions struct {
|
||||
NotBefore time.Time
|
||||
NotAfter time.Time
|
||||
}
|
||||
|
||||
type OrderService service
|
||||
|
||||
// New Creates a new order.
|
||||
func (o *OrderService) New(domains []string) (acme.ExtendedOrder, error) {
|
||||
return o.NewWithOptions(domains, nil)
|
||||
}
|
||||
|
||||
// NewWithOptions Creates a new order.
|
||||
func (o *OrderService) NewWithOptions(domains []string, opts *OrderOptions) (acme.ExtendedOrder, error) {
|
||||
var identifiers []acme.Identifier
|
||||
for _, domain := range domains {
|
||||
ident := acme.Identifier{Value: domain, Type: "dns"}
|
||||
|
||||
if net.ParseIP(domain) != nil {
|
||||
ident.Type = "ip"
|
||||
}
|
||||
|
||||
identifiers = append(identifiers, ident)
|
||||
}
|
||||
|
||||
orderReq := acme.Order{Identifiers: identifiers}
|
||||
|
||||
if opts != nil {
|
||||
if !opts.NotAfter.IsZero() {
|
||||
orderReq.NotAfter = opts.NotAfter.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
if !opts.NotBefore.IsZero() {
|
||||
orderReq.NotBefore = opts.NotBefore.Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
|
||||
var order acme.Order
|
||||
resp, err := o.core.post(o.core.GetDirectory().NewOrderURL, orderReq, &order)
|
||||
if err != nil {
|
||||
return acme.ExtendedOrder{}, err
|
||||
}
|
||||
|
||||
return acme.ExtendedOrder{
|
||||
Order: order,
|
||||
Location: resp.Header.Get("Location"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Get Gets an order.
|
||||
func (o *OrderService) Get(orderURL string) (acme.ExtendedOrder, error) {
|
||||
if orderURL == "" {
|
||||
return acme.ExtendedOrder{}, errors.New("order[get]: empty URL")
|
||||
}
|
||||
|
||||
var order acme.Order
|
||||
_, err := o.core.postAsGet(orderURL, &order)
|
||||
if err != nil {
|
||||
return acme.ExtendedOrder{}, err
|
||||
}
|
||||
|
||||
return acme.ExtendedOrder{Order: order}, nil
|
||||
}
|
||||
|
||||
// UpdateForCSR Updates an order for a CSR.
|
||||
func (o *OrderService) UpdateForCSR(orderURL string, csr []byte) (acme.ExtendedOrder, error) {
|
||||
csrMsg := acme.CSRMessage{
|
||||
Csr: base64.RawURLEncoding.EncodeToString(csr),
|
||||
}
|
||||
|
||||
var order acme.Order
|
||||
_, err := o.core.post(orderURL, csrMsg, &order)
|
||||
if err != nil {
|
||||
return acme.ExtendedOrder{}, err
|
||||
}
|
||||
|
||||
if order.Status == acme.StatusInvalid {
|
||||
return acme.ExtendedOrder{}, order.Error
|
||||
}
|
||||
|
||||
return acme.ExtendedOrder{Order: order}, nil
|
||||
}
|
129
acme/api/order_test.go
Normal file
129
acme/api/order_test.go
Normal file
|
@ -0,0 +1,129 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/go-jose/go-jose/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestOrderService_NewWithOptions(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
// small value keeps test fast
|
||||
privateKey, errK := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, errK, "Could not generate test key")
|
||||
|
||||
mux.HandleFunc("/newOrder", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := readSignedBody(r, privateKey)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
order := acme.Order{}
|
||||
err = json.Unmarshal(body, &order)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = tester.WriteJSONResponse(w, acme.Order{
|
||||
Status: acme.StatusValid,
|
||||
Expires: order.Expires,
|
||||
Identifiers: order.Identifiers,
|
||||
NotBefore: order.NotBefore,
|
||||
NotAfter: order.NotAfter,
|
||||
Error: order.Error,
|
||||
Authorizations: order.Authorizations,
|
||||
Finalize: order.Finalize,
|
||||
Certificate: order.Certificate,
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
core, err := New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
opts *OrderOptions
|
||||
expected acme.ExtendedOrder
|
||||
}{
|
||||
{
|
||||
desc: "simple",
|
||||
expected: acme.ExtendedOrder{
|
||||
Order: acme.Order{
|
||||
Status: "valid",
|
||||
Identifiers: []acme.Identifier{{Type: "dns", Value: "example.com"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "with options",
|
||||
opts: &OrderOptions{
|
||||
NotBefore: time.Date(2023, 1, 1, 1, 0, 0, 0, time.UTC),
|
||||
NotAfter: time.Date(2023, 1, 2, 1, 0, 0, 0, time.UTC),
|
||||
},
|
||||
expected: acme.ExtendedOrder{
|
||||
Order: acme.Order{
|
||||
Status: "valid",
|
||||
Identifiers: []acme.Identifier{{Type: "dns", Value: "example.com"}},
|
||||
NotBefore: "2023-01-01T01:00:00Z",
|
||||
NotAfter: "2023-01-02T01:00:00Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
order, err := core.Orders.NewWithOptions([]string{"example.com"}, test.opts)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, test.expected, order)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func readSignedBody(r *http.Request, privateKey *rsa.PrivateKey) ([]byte, error) {
|
||||
reqBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
jws, err := jose.ParseSigned(string(reqBody))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := jws.Verify(&jose.JSONWebKey{
|
||||
Key: privateKey.Public(),
|
||||
Algorithm: "RSA",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
53
acme/api/renewal.go
Normal file
53
acme/api/renewal.go
Normal file
|
@ -0,0 +1,53 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
// ErrNoARI is returned when the server does not advertise a renewal info endpoint.
|
||||
var ErrNoARI = errors.New("renewalInfo[get/post]: server does not advertise a renewal info endpoint")
|
||||
|
||||
// GetRenewalInfo GETs renewal information for a certificate from the renewalInfo endpoint.
|
||||
// This is used to determine if a certificate needs to be renewed.
|
||||
//
|
||||
// Note: this endpoint is part of a draft specification, not all ACME servers will implement it.
|
||||
// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint.
|
||||
//
|
||||
// https://datatracker.ietf.org/doc/draft-ietf-acme-ari
|
||||
func (c *CertificateService) GetRenewalInfo(certID string) (*http.Response, error) {
|
||||
if c.core.GetDirectory().RenewalInfo == "" {
|
||||
return nil, ErrNoARI
|
||||
}
|
||||
|
||||
if certID == "" {
|
||||
return nil, errors.New("renewalInfo[get]: 'certID' cannot be empty")
|
||||
}
|
||||
|
||||
return c.core.HTTPClient.Get(c.core.GetDirectory().RenewalInfo + "/" + certID)
|
||||
}
|
||||
|
||||
// UpdateRenewalInfo POSTs updated renewal information for a certificate to the renewalInfo endpoint.
|
||||
// This is used to indicate that a certificate has been replaced.
|
||||
//
|
||||
// Note: this endpoint is part of a draft specification, not all ACME servers will implement it.
|
||||
// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint.
|
||||
//
|
||||
// https://datatracker.ietf.org/doc/draft-ietf-acme-ari
|
||||
func (c *CertificateService) UpdateRenewalInfo(req acme.RenewalInfoUpdateRequest) (*http.Response, error) {
|
||||
if c.core.GetDirectory().RenewalInfo == "" {
|
||||
return nil, ErrNoARI
|
||||
}
|
||||
|
||||
if req.CertID == "" {
|
||||
return nil, errors.New("renewalInfo[post]: 'certID' cannot be empty")
|
||||
}
|
||||
|
||||
if !req.Replaced {
|
||||
return nil, errors.New("renewalInfo[post]: 'replaced' cannot be false")
|
||||
}
|
||||
|
||||
return c.core.post(c.core.GetDirectory().RenewalInfo, req, nil)
|
||||
}
|
56
acme/api/service.go
Normal file
56
acme/api/service.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type service struct {
|
||||
core *Core
|
||||
}
|
||||
|
||||
// getLink get a rel into the Link header.
|
||||
func getLink(header http.Header, rel string) string {
|
||||
links := getLinks(header, rel)
|
||||
if len(links) < 1 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return links[0]
|
||||
}
|
||||
|
||||
func getLinks(header http.Header, rel string) []string {
|
||||
linkExpr := regexp.MustCompile(`<(.+?)>(?:;[^;]+)*?;\s*rel="(.+?)"`)
|
||||
|
||||
var links []string
|
||||
for _, link := range header["Link"] {
|
||||
for _, m := range linkExpr.FindAllStringSubmatch(link, -1) {
|
||||
if len(m) != 3 {
|
||||
continue
|
||||
}
|
||||
if m[2] == rel {
|
||||
links = append(links, m[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return links
|
||||
}
|
||||
|
||||
// getLocation get the value of the header Location.
|
||||
func getLocation(resp *http.Response) string {
|
||||
if resp == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return resp.Header.Get("Location")
|
||||
}
|
||||
|
||||
// getRetryAfter get the value of the header Retry-After.
|
||||
func getRetryAfter(resp *http.Response) string {
|
||||
if resp == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return resp.Header.Get("Retry-After")
|
||||
}
|
56
acme/api/service_test.go
Normal file
56
acme/api/service_test.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_getLink(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
header http.Header
|
||||
relName string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
header: http.Header{
|
||||
"Link": []string{`<https://acme-staging-v02.api.letsencrypt.org/next>; rel="next", <https://acme-staging-v02.api.letsencrypt.org/up?query>; rel="up"`},
|
||||
},
|
||||
relName: "up",
|
||||
expected: "https://acme-staging-v02.api.letsencrypt.org/up?query",
|
||||
},
|
||||
{
|
||||
desc: "success several lines",
|
||||
header: http.Header{
|
||||
"Link": []string{`<https://acme-staging-v02.api.letsencrypt.org/next>; rel="next"`, `<https://acme-staging-v02.api.letsencrypt.org/up?query>; rel="up"`},
|
||||
},
|
||||
relName: "up",
|
||||
expected: "https://acme-staging-v02.api.letsencrypt.org/up?query",
|
||||
},
|
||||
{
|
||||
desc: "no link",
|
||||
header: http.Header{},
|
||||
relName: "up",
|
||||
expected: "",
|
||||
},
|
||||
{
|
||||
desc: "no header",
|
||||
relName: "up",
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
link := getLink(test.header, test.relName)
|
||||
|
||||
assert.Equal(t, test.expected, link)
|
||||
})
|
||||
}
|
||||
}
|
341
acme/commons.go
Normal file
341
acme/commons.go
Normal file
|
@ -0,0 +1,341 @@
|
|||
// Package acme contains all objects related the ACME endpoints.
|
||||
// https://www.rfc-editor.org/rfc/rfc8555.html
|
||||
package acme
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ACME status values of Account, Order, Authorization and Challenge objects.
|
||||
// See https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.6 for details.
|
||||
const (
|
||||
StatusDeactivated = "deactivated"
|
||||
StatusExpired = "expired"
|
||||
StatusInvalid = "invalid"
|
||||
StatusPending = "pending"
|
||||
StatusProcessing = "processing"
|
||||
StatusReady = "ready"
|
||||
StatusRevoked = "revoked"
|
||||
StatusUnknown = "unknown"
|
||||
StatusValid = "valid"
|
||||
)
|
||||
|
||||
// CRL reason codes as defined in RFC 5280.
|
||||
// https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1
|
||||
const (
|
||||
CRLReasonUnspecified uint = 0
|
||||
CRLReasonKeyCompromise uint = 1
|
||||
CRLReasonCACompromise uint = 2
|
||||
CRLReasonAffiliationChanged uint = 3
|
||||
CRLReasonSuperseded uint = 4
|
||||
CRLReasonCessationOfOperation uint = 5
|
||||
CRLReasonCertificateHold uint = 6
|
||||
CRLReasonRemoveFromCRL uint = 8
|
||||
CRLReasonPrivilegeWithdrawn uint = 9
|
||||
CRLReasonAACompromise uint = 10
|
||||
)
|
||||
|
||||
// Directory the ACME directory object.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.1
|
||||
// - https://datatracker.ietf.org/doc/draft-ietf-acme-ari/
|
||||
type Directory struct {
|
||||
NewNonceURL string `json:"newNonce"`
|
||||
NewAccountURL string `json:"newAccount"`
|
||||
NewOrderURL string `json:"newOrder"`
|
||||
NewAuthzURL string `json:"newAuthz"`
|
||||
RevokeCertURL string `json:"revokeCert"`
|
||||
KeyChangeURL string `json:"keyChange"`
|
||||
Meta Meta `json:"meta"`
|
||||
RenewalInfo string `json:"renewalInfo"`
|
||||
}
|
||||
|
||||
// Meta the ACME meta object (related to Directory).
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.1
|
||||
type Meta struct {
|
||||
// termsOfService (optional, string):
|
||||
// A URL identifying the current terms of service.
|
||||
TermsOfService string `json:"termsOfService"`
|
||||
|
||||
// website (optional, string):
|
||||
// An HTTP or HTTPS URL locating a website providing more information about the ACME server.
|
||||
Website string `json:"website"`
|
||||
|
||||
// caaIdentities (optional, array of string):
|
||||
// The hostnames that the ACME server recognizes as referring to itself
|
||||
// for the purposes of CAA record validation as defined in [RFC6844].
|
||||
// Each string MUST represent the same sequence of ASCII code points
|
||||
// that the server will expect to see as the "Issuer Domain Name" in a CAA issue or issuewild property tag.
|
||||
// This allows clients to determine the correct issuer domain name to use when configuring CAA records.
|
||||
CaaIdentities []string `json:"caaIdentities"`
|
||||
|
||||
// externalAccountRequired (optional, boolean):
|
||||
// If this field is present and set to "true",
|
||||
// then the CA requires that all new- account requests include an "externalAccountBinding" field
|
||||
// associating the new account with an external account.
|
||||
ExternalAccountRequired bool `json:"externalAccountRequired"`
|
||||
}
|
||||
|
||||
// ExtendedAccount a extended Account.
|
||||
type ExtendedAccount struct {
|
||||
Account
|
||||
// Contains the value of the response header `Location`
|
||||
Location string `json:"-"`
|
||||
}
|
||||
|
||||
// Account the ACME account Object.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.2
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.3
|
||||
type Account struct {
|
||||
// status (required, string):
|
||||
// The status of this account.
|
||||
// Possible values are: "valid", "deactivated", and "revoked".
|
||||
// The value "deactivated" should be used to indicate client-initiated deactivation
|
||||
// whereas "revoked" should be used to indicate server- initiated deactivation. (See Section 7.1.6)
|
||||
Status string `json:"status,omitempty"`
|
||||
|
||||
// contact (optional, array of string):
|
||||
// An array of URLs that the server can use to contact the client for issues related to this account.
|
||||
// For example, the server may wish to notify the client about server-initiated revocation or certificate expiration.
|
||||
// For information on supported URL schemes, see Section 7.3
|
||||
Contact []string `json:"contact,omitempty"`
|
||||
|
||||
// termsOfServiceAgreed (optional, boolean):
|
||||
// Including this field in a new-account request,
|
||||
// with a value of true, indicates the client's agreement with the terms of service.
|
||||
// This field is not updateable by the client.
|
||||
TermsOfServiceAgreed bool `json:"termsOfServiceAgreed,omitempty"`
|
||||
|
||||
// orders (required, string):
|
||||
// A URL from which a list of orders submitted by this account can be fetched via a POST-as-GET request,
|
||||
// as described in Section 7.1.2.1.
|
||||
Orders string `json:"orders,omitempty"`
|
||||
|
||||
// onlyReturnExisting (optional, boolean):
|
||||
// If this field is present with the value "true",
|
||||
// then the server MUST NOT create a new account if one does not already exist.
|
||||
// This allows a client to look up an account URL based on an account key (see Section 7.3.1).
|
||||
OnlyReturnExisting bool `json:"onlyReturnExisting,omitempty"`
|
||||
|
||||
// externalAccountBinding (optional, object):
|
||||
// An optional field for binding the new account with an existing non-ACME account (see Section 7.3.4).
|
||||
ExternalAccountBinding json.RawMessage `json:"externalAccountBinding,omitempty"`
|
||||
}
|
||||
|
||||
// ExtendedOrder a extended Order.
|
||||
type ExtendedOrder struct {
|
||||
Order
|
||||
|
||||
// The order URL, contains the value of the response header `Location`
|
||||
Location string `json:"-"`
|
||||
}
|
||||
|
||||
// Order the ACME order Object.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.3
|
||||
type Order struct {
|
||||
// status (required, string):
|
||||
// The status of this order.
|
||||
// Possible values are: "pending", "ready", "processing", "valid", and "invalid".
|
||||
Status string `json:"status,omitempty"`
|
||||
|
||||
// expires (optional, string):
|
||||
// The timestamp after which the server will consider this order invalid,
|
||||
// encoded in the format specified in RFC 3339 [RFC3339].
|
||||
// This field is REQUIRED for objects with "pending" or "valid" in the status field.
|
||||
Expires string `json:"expires,omitempty"`
|
||||
|
||||
// identifiers (required, array of object):
|
||||
// An array of identifier objects that the order pertains to.
|
||||
Identifiers []Identifier `json:"identifiers"`
|
||||
|
||||
// notBefore (optional, string):
|
||||
// The requested value of the notBefore field in the certificate,
|
||||
// in the date format defined in [RFC3339].
|
||||
NotBefore string `json:"notBefore,omitempty"`
|
||||
|
||||
// notAfter (optional, string):
|
||||
// The requested value of the notAfter field in the certificate,
|
||||
// in the date format defined in [RFC3339].
|
||||
NotAfter string `json:"notAfter,omitempty"`
|
||||
|
||||
// error (optional, object):
|
||||
// The error that occurred while processing the order, if any.
|
||||
// This field is structured as a problem document [RFC7807].
|
||||
Error *ProblemDetails `json:"error,omitempty"`
|
||||
|
||||
// authorizations (required, array of string):
|
||||
// For pending orders,
|
||||
// the authorizations that the client needs to complete before the requested certificate can be issued (see Section 7.5),
|
||||
// including unexpired authorizations that the client has completed in the past for identifiers specified in the order.
|
||||
// The authorizations required are dictated by server policy
|
||||
// and there may not be a 1:1 relationship between the order identifiers and the authorizations required.
|
||||
// For final orders (in the "valid" or "invalid" state), the authorizations that were completed.
|
||||
// Each entry is a URL from which an authorization can be fetched with a POST-as-GET request.
|
||||
Authorizations []string `json:"authorizations,omitempty"`
|
||||
|
||||
// finalize (required, string):
|
||||
// A URL that a CSR must be POSTed to once all of the order's authorizations are satisfied to finalize the order.
|
||||
// The result of a successful finalization will be the population of the certificate URL for the order.
|
||||
Finalize string `json:"finalize,omitempty"`
|
||||
|
||||
// certificate (optional, string):
|
||||
// A URL for the certificate that has been issued in response to this order
|
||||
Certificate string `json:"certificate,omitempty"`
|
||||
}
|
||||
|
||||
// Authorization the ACME authorization object.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.4
|
||||
type Authorization struct {
|
||||
// status (required, string):
|
||||
// The status of this authorization.
|
||||
// Possible values are: "pending", "valid", "invalid", "deactivated", "expired", and "revoked".
|
||||
Status string `json:"status"`
|
||||
|
||||
// expires (optional, string):
|
||||
// The timestamp after which the server will consider this authorization invalid,
|
||||
// encoded in the format specified in RFC 3339 [RFC3339].
|
||||
// This field is REQUIRED for objects with "valid" in the "status" field.
|
||||
Expires time.Time `json:"expires,omitempty"`
|
||||
|
||||
// identifier (required, object):
|
||||
// The identifier that the account is authorized to represent
|
||||
Identifier Identifier `json:"identifier,omitempty"`
|
||||
|
||||
// challenges (required, array of objects):
|
||||
// For pending authorizations, the challenges that the client can fulfill in order to prove possession of the identifier.
|
||||
// For valid authorizations, the challenge that was validated.
|
||||
// For invalid authorizations, the challenge that was attempted and failed.
|
||||
// Each array entry is an object with parameters required to validate the challenge.
|
||||
// A client should attempt to fulfill one of these challenges,
|
||||
// and a server should consider any one of the challenges sufficient to make the authorization valid.
|
||||
Challenges []Challenge `json:"challenges,omitempty"`
|
||||
|
||||
// wildcard (optional, boolean):
|
||||
// For authorizations created as a result of a newOrder request containing a DNS identifier
|
||||
// with a value that contained a wildcard prefix this field MUST be present, and true.
|
||||
Wildcard bool `json:"wildcard,omitempty"`
|
||||
}
|
||||
|
||||
// ExtendedChallenge a extended Challenge.
|
||||
type ExtendedChallenge struct {
|
||||
Challenge
|
||||
// Contains the value of the response header `Retry-After`
|
||||
RetryAfter string `json:"-"`
|
||||
// Contains the value of the response header `Link` rel="up"
|
||||
AuthorizationURL string `json:"-"`
|
||||
}
|
||||
|
||||
// Challenge the ACME challenge object.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.5
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-8
|
||||
type Challenge struct {
|
||||
// type (required, string):
|
||||
// The type of challenge encoded in the object.
|
||||
Type string `json:"type"`
|
||||
|
||||
// url (required, string):
|
||||
// The URL to which a response can be posted.
|
||||
URL string `json:"url"`
|
||||
|
||||
// status (required, string):
|
||||
// The status of this challenge. Possible values are: "pending", "processing", "valid", and "invalid".
|
||||
Status string `json:"status"`
|
||||
|
||||
// validated (optional, string):
|
||||
// The time at which the server validated this challenge,
|
||||
// encoded in the format specified in RFC 3339 [RFC3339].
|
||||
// This field is REQUIRED if the "status" field is "valid".
|
||||
Validated time.Time `json:"validated,omitempty"`
|
||||
|
||||
// error (optional, object):
|
||||
// Error that occurred while the server was validating the challenge, if any,
|
||||
// structured as a problem document [RFC7807].
|
||||
// Multiple errors can be indicated by using subproblems Section 6.7.1.
|
||||
// A challenge object with an error MUST have status equal to "invalid".
|
||||
Error *ProblemDetails `json:"error,omitempty"`
|
||||
|
||||
// token (required, string):
|
||||
// A random value that uniquely identifies the challenge.
|
||||
// This value MUST have at least 128 bits of entropy.
|
||||
// It MUST NOT contain any characters outside the base64url alphabet,
|
||||
// and MUST NOT include base64 padding characters ("=").
|
||||
// See [RFC4086] for additional information on randomness requirements.
|
||||
// https://www.rfc-editor.org/rfc/rfc8555.html#section-8.3
|
||||
// https://www.rfc-editor.org/rfc/rfc8555.html#section-8.4
|
||||
Token string `json:"token"`
|
||||
|
||||
// https://www.rfc-editor.org/rfc/rfc8555.html#section-8.1
|
||||
KeyAuthorization string `json:"keyAuthorization"`
|
||||
}
|
||||
|
||||
// Identifier the ACME identifier object.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-9.7.7
|
||||
type Identifier struct {
|
||||
Type string `json:"type"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// CSRMessage Certificate Signing Request.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.4
|
||||
type CSRMessage struct {
|
||||
// csr (required, string):
|
||||
// A CSR encoding the parameters for the certificate being requested [RFC2986].
|
||||
// The CSR is sent in the base64url-encoded version of the DER format.
|
||||
// (Note: Because this field uses base64url, and does not include headers, it is different from PEM.).
|
||||
Csr string `json:"csr"`
|
||||
}
|
||||
|
||||
// RevokeCertMessage a certificate revocation message.
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.6
|
||||
// - https://www.rfc-editor.org/rfc/rfc5280.html#section-5.3.1
|
||||
type RevokeCertMessage struct {
|
||||
// certificate (required, string):
|
||||
// The certificate to be revoked, in the base64url-encoded version of the DER format.
|
||||
// (Note: Because this field uses base64url, and does not include headers, it is different from PEM.)
|
||||
Certificate string `json:"certificate"`
|
||||
|
||||
// reason (optional, int):
|
||||
// One of the revocation reasonCodes defined in Section 5.3.1 of [RFC5280] to be used when generating OCSP responses and CRLs.
|
||||
// If this field is not set the server SHOULD omit the reasonCode CRL entry extension when generating OCSP responses and CRLs.
|
||||
// The server MAY disallow a subset of reasonCodes from being used by the user.
|
||||
// If a request contains a disallowed reasonCode the server MUST reject it with the error type "urn:ietf:params:acme:error:badRevocationReason".
|
||||
// The problem document detail SHOULD indicate which reasonCodes are allowed.
|
||||
Reason *uint `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// RawCertificate raw data of a certificate.
|
||||
type RawCertificate struct {
|
||||
Cert []byte
|
||||
Issuer []byte
|
||||
}
|
||||
|
||||
// Window is a window of time.
|
||||
type Window struct {
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
}
|
||||
|
||||
// RenewalInfoResponse is the response to GET requests made the renewalInfo endpoint.
|
||||
// - (4.1. Getting Renewal Information) https://datatracker.ietf.org/doc/draft-ietf-acme-ari/
|
||||
type RenewalInfoResponse struct {
|
||||
// SuggestedWindow contains two fields, start and end,
|
||||
// whose values are timestamps which bound the window of time in which the CA recommends renewing the certificate.
|
||||
SuggestedWindow Window `json:"suggestedWindow"`
|
||||
// ExplanationURL is a optional URL pointing to a page which may explain why the suggested renewal window is what it is.
|
||||
// For example, it may be a page explaining the CA's dynamic load-balancing strategy,
|
||||
// or a page documenting which certificates are affected by a mass revocation event.
|
||||
// Callers SHOULD provide this URL to their operator, if present.
|
||||
ExplanationURL string `json:"explanationURL"`
|
||||
}
|
||||
|
||||
// RenewalInfoUpdateRequest is the JWS payload for POST requests made to the renewalInfo endpoint.
|
||||
// - (4.2. Updating Renewal Information) https://datatracker.ietf.org/doc/draft-ietf-acme-ari/
|
||||
type RenewalInfoUpdateRequest struct {
|
||||
// CertID is the base64url-encoded [RFC4648] bytes of a DER-encoded CertID ASN.1 sequence [RFC6960] with any trailing '=' characters stripped.
|
||||
CertID string `json:"certID"`
|
||||
// Replaced is required and indicates whether or not the client considers the certificate to have been replaced.
|
||||
// A certificate is considered replaced when its revocation would not disrupt any ongoing services,
|
||||
// for instance because it has been renewed and the new certificate is in use, or because it is no longer in use.
|
||||
// Clients SHOULD NOT send a request where this value is false.
|
||||
Replaced bool `json:"replaced"`
|
||||
}
|
58
acme/errors.go
Normal file
58
acme/errors.go
Normal file
|
@ -0,0 +1,58 @@
|
|||
package acme
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Errors types.
|
||||
const (
|
||||
errNS = "urn:ietf:params:acme:error:"
|
||||
BadNonceErr = errNS + "badNonce"
|
||||
)
|
||||
|
||||
// ProblemDetails the problem details object.
|
||||
// - https://www.rfc-editor.org/rfc/rfc7807.html#section-3.1
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-7.3.3
|
||||
type ProblemDetails struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
HTTPStatus int `json:"status,omitempty"`
|
||||
Instance string `json:"instance,omitempty"`
|
||||
SubProblems []SubProblem `json:"subproblems,omitempty"`
|
||||
|
||||
// additional values to have a better error message (Not defined by the RFC)
|
||||
Method string `json:"method,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
}
|
||||
|
||||
// SubProblem a "subproblems".
|
||||
// - https://www.rfc-editor.org/rfc/rfc8555.html#section-6.7.1
|
||||
type SubProblem struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Identifier Identifier `json:"identifier,omitempty"`
|
||||
}
|
||||
|
||||
func (p ProblemDetails) Error() string {
|
||||
msg := fmt.Sprintf("acme: error: %d", p.HTTPStatus)
|
||||
if p.Method != "" || p.URL != "" {
|
||||
msg += fmt.Sprintf(" :: %s :: %s", p.Method, p.URL)
|
||||
}
|
||||
msg += fmt.Sprintf(" :: %s :: %s", p.Type, p.Detail)
|
||||
|
||||
for _, sub := range p.SubProblems {
|
||||
msg += fmt.Sprintf(", problem: %q :: %s", sub.Type, sub.Detail)
|
||||
}
|
||||
|
||||
if p.Instance != "" {
|
||||
msg += ", url: " + p.Instance
|
||||
}
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
// NonceError represents the error which is returned
|
||||
// if the nonce sent by the client was not accepted by the server.
|
||||
type NonceError struct {
|
||||
*ProblemDetails
|
||||
}
|
10
buildx.Dockerfile
Normal file
10
buildx.Dockerfile
Normal file
|
@ -0,0 +1,10 @@
|
|||
# syntax=docker/dockerfile:1.4
|
||||
FROM alpine:3
|
||||
|
||||
RUN apk --no-cache --no-progress add git ca-certificates tzdata \
|
||||
&& rm -rf /var/cache/apk/*
|
||||
|
||||
COPY lego /
|
||||
|
||||
ENTRYPOINT ["/lego"]
|
||||
EXPOSE 80
|
File diff suppressed because it is too large
Load diff
|
@ -1,10 +0,0 @@
|
|||
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
|
||||
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
||||
<channel>
|
||||
<title>Categories on Let’s Encrypt client and ACME library written in Go.</title>
|
||||
<link>https://go-acme.github.io/lego/categories/</link>
|
||||
<description>Recent content in Categories on Let’s Encrypt client and ACME library written in Go.</description>
|
||||
<generator>Hugo -- gohugo.io</generator>
|
||||
<language>en-us</language><atom:link href="https://go-acme.github.io/lego/categories/index.xml" rel="self" type="application/rss+xml" />
|
||||
</channel>
|
||||
</rss>
|
320
certcrypto/crypto.go
Normal file
320
certcrypto/crypto.go
Normal file
|
@ -0,0 +1,320 @@
|
|||
package certcrypto
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/asn1"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ocsp"
|
||||
)
|
||||
|
||||
// Constants for all key types we support.
|
||||
const (
|
||||
EC256 = KeyType("P256")
|
||||
EC384 = KeyType("P384")
|
||||
RSA2048 = KeyType("2048")
|
||||
RSA3072 = KeyType("3072")
|
||||
RSA4096 = KeyType("4096")
|
||||
RSA8192 = KeyType("8192")
|
||||
)
|
||||
|
||||
const (
|
||||
// OCSPGood means that the certificate is valid.
|
||||
OCSPGood = ocsp.Good
|
||||
// OCSPRevoked means that the certificate has been deliberately revoked.
|
||||
OCSPRevoked = ocsp.Revoked
|
||||
// OCSPUnknown means that the OCSP responder doesn't know about the certificate.
|
||||
OCSPUnknown = ocsp.Unknown
|
||||
// OCSPServerFailed means that the OCSP responder failed to process the request.
|
||||
OCSPServerFailed = ocsp.ServerFailed
|
||||
)
|
||||
|
||||
// Constants for OCSP must staple.
|
||||
var (
|
||||
tlsFeatureExtensionOID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 24}
|
||||
ocspMustStapleFeature = []byte{0x30, 0x03, 0x02, 0x01, 0x05}
|
||||
)
|
||||
|
||||
// KeyType represents the key algo as well as the key size or curve to use.
|
||||
type KeyType string
|
||||
|
||||
type DERCertificateBytes []byte
|
||||
|
||||
// ParsePEMBundle parses a certificate bundle from top to bottom and returns
|
||||
// a slice of x509 certificates. This function will error if no certificates are found.
|
||||
func ParsePEMBundle(bundle []byte) ([]*x509.Certificate, error) {
|
||||
var certificates []*x509.Certificate
|
||||
var certDERBlock *pem.Block
|
||||
|
||||
for {
|
||||
certDERBlock, bundle = pem.Decode(bundle)
|
||||
if certDERBlock == nil {
|
||||
break
|
||||
}
|
||||
|
||||
if certDERBlock.Type == "CERTIFICATE" {
|
||||
cert, err := x509.ParseCertificate(certDERBlock.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
certificates = append(certificates, cert)
|
||||
}
|
||||
}
|
||||
|
||||
if len(certificates) == 0 {
|
||||
return nil, errors.New("no certificates were found while parsing the bundle")
|
||||
}
|
||||
|
||||
return certificates, nil
|
||||
}
|
||||
|
||||
// ParsePEMPrivateKey parses a private key from key, which is a PEM block.
|
||||
// Borrowed from Go standard library, to handle various private key and PEM block types.
|
||||
// https://github.com/golang/go/blob/693748e9fa385f1e2c3b91ca9acbb6c0ad2d133d/src/crypto/tls/tls.go#L291-L308
|
||||
// https://github.com/golang/go/blob/693748e9fa385f1e2c3b91ca9acbb6c0ad2d133d/src/crypto/tls/tls.go#L238)
|
||||
func ParsePEMPrivateKey(key []byte) (crypto.PrivateKey, error) {
|
||||
keyBlockDER, _ := pem.Decode(key)
|
||||
if keyBlockDER == nil {
|
||||
return nil, fmt.Errorf("invalid PEM block")
|
||||
}
|
||||
|
||||
if keyBlockDER.Type != "PRIVATE KEY" && !strings.HasSuffix(keyBlockDER.Type, " PRIVATE KEY") {
|
||||
return nil, fmt.Errorf("unknown PEM header %q", keyBlockDER.Type)
|
||||
}
|
||||
|
||||
if key, err := x509.ParsePKCS1PrivateKey(keyBlockDER.Bytes); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
if key, err := x509.ParsePKCS8PrivateKey(keyBlockDER.Bytes); err == nil {
|
||||
switch key := key.(type) {
|
||||
case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
|
||||
return key, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("found unknown private key type in PKCS#8 wrapping: %T", key)
|
||||
}
|
||||
}
|
||||
|
||||
if key, err := x509.ParseECPrivateKey(keyBlockDER.Bytes); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("failed to parse private key")
|
||||
}
|
||||
|
||||
func GeneratePrivateKey(keyType KeyType) (crypto.PrivateKey, error) {
|
||||
switch keyType {
|
||||
case EC256:
|
||||
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
case EC384:
|
||||
return ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
|
||||
case RSA2048:
|
||||
return rsa.GenerateKey(rand.Reader, 2048)
|
||||
case RSA3072:
|
||||
return rsa.GenerateKey(rand.Reader, 3072)
|
||||
case RSA4096:
|
||||
return rsa.GenerateKey(rand.Reader, 4096)
|
||||
case RSA8192:
|
||||
return rsa.GenerateKey(rand.Reader, 8192)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid KeyType: %s", keyType)
|
||||
}
|
||||
|
||||
func GenerateCSR(privateKey crypto.PrivateKey, domain string, san []string, mustStaple bool) ([]byte, error) {
|
||||
var dnsNames []string
|
||||
var ipAddresses []net.IP
|
||||
for _, altname := range san {
|
||||
if ip := net.ParseIP(altname); ip != nil {
|
||||
ipAddresses = append(ipAddresses, ip)
|
||||
} else {
|
||||
dnsNames = append(dnsNames, altname)
|
||||
}
|
||||
}
|
||||
|
||||
template := x509.CertificateRequest{
|
||||
Subject: pkix.Name{CommonName: domain},
|
||||
DNSNames: dnsNames,
|
||||
IPAddresses: ipAddresses,
|
||||
}
|
||||
|
||||
if mustStaple {
|
||||
template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{
|
||||
Id: tlsFeatureExtensionOID,
|
||||
Value: ocspMustStapleFeature,
|
||||
})
|
||||
}
|
||||
|
||||
return x509.CreateCertificateRequest(rand.Reader, &template, privateKey)
|
||||
}
|
||||
|
||||
func PEMEncode(data interface{}) []byte {
|
||||
return pem.EncodeToMemory(PEMBlock(data))
|
||||
}
|
||||
|
||||
func PEMBlock(data interface{}) *pem.Block {
|
||||
var pemBlock *pem.Block
|
||||
switch key := data.(type) {
|
||||
case *ecdsa.PrivateKey:
|
||||
keyBytes, _ := x509.MarshalECPrivateKey(key)
|
||||
pemBlock = &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}
|
||||
case *rsa.PrivateKey:
|
||||
pemBlock = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}
|
||||
case *x509.CertificateRequest:
|
||||
pemBlock = &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: key.Raw}
|
||||
case DERCertificateBytes:
|
||||
pemBlock = &pem.Block{Type: "CERTIFICATE", Bytes: []byte(data.(DERCertificateBytes))}
|
||||
}
|
||||
|
||||
return pemBlock
|
||||
}
|
||||
|
||||
func pemDecode(data []byte) (*pem.Block, error) {
|
||||
pemBlock, _ := pem.Decode(data)
|
||||
if pemBlock == nil {
|
||||
return nil, errors.New("PEM decode did not yield a valid block. Is the certificate in the right format?")
|
||||
}
|
||||
|
||||
return pemBlock, nil
|
||||
}
|
||||
|
||||
func PemDecodeTox509CSR(data []byte) (*x509.CertificateRequest, error) {
|
||||
pemBlock, err := pemDecode(data)
|
||||
if pemBlock == nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if pemBlock.Type != "CERTIFICATE REQUEST" && pemBlock.Type != "NEW CERTIFICATE REQUEST" {
|
||||
return nil, errors.New("PEM block is not a certificate request")
|
||||
}
|
||||
|
||||
return x509.ParseCertificateRequest(pemBlock.Bytes)
|
||||
}
|
||||
|
||||
// ParsePEMCertificate returns Certificate from a PEM encoded certificate.
|
||||
// The certificate has to be PEM encoded. Any other encodings like DER will fail.
|
||||
func ParsePEMCertificate(cert []byte) (*x509.Certificate, error) {
|
||||
pemBlock, err := pemDecode(cert)
|
||||
if pemBlock == nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// from a DER encoded certificate
|
||||
return x509.ParseCertificate(pemBlock.Bytes)
|
||||
}
|
||||
|
||||
func ExtractDomains(cert *x509.Certificate) []string {
|
||||
var domains []string
|
||||
if cert.Subject.CommonName != "" {
|
||||
domains = append(domains, cert.Subject.CommonName)
|
||||
}
|
||||
|
||||
// Check for SAN certificate
|
||||
for _, sanDomain := range cert.DNSNames {
|
||||
if sanDomain == cert.Subject.CommonName {
|
||||
continue
|
||||
}
|
||||
domains = append(domains, sanDomain)
|
||||
}
|
||||
|
||||
commonNameIP := net.ParseIP(cert.Subject.CommonName)
|
||||
for _, sanIP := range cert.IPAddresses {
|
||||
if !commonNameIP.Equal(sanIP) {
|
||||
domains = append(domains, sanIP.String())
|
||||
}
|
||||
}
|
||||
|
||||
return domains
|
||||
}
|
||||
|
||||
func ExtractDomainsCSR(csr *x509.CertificateRequest) []string {
|
||||
var domains []string
|
||||
if csr.Subject.CommonName != "" {
|
||||
domains = append(domains, csr.Subject.CommonName)
|
||||
}
|
||||
|
||||
// loop over the SubjectAltName DNS names
|
||||
for _, sanName := range csr.DNSNames {
|
||||
if containsSAN(domains, sanName) {
|
||||
// Duplicate; skip this name
|
||||
continue
|
||||
}
|
||||
|
||||
// Name is unique
|
||||
domains = append(domains, sanName)
|
||||
}
|
||||
|
||||
cnip := net.ParseIP(csr.Subject.CommonName)
|
||||
for _, sanIP := range csr.IPAddresses {
|
||||
if !cnip.Equal(sanIP) {
|
||||
domains = append(domains, sanIP.String())
|
||||
}
|
||||
}
|
||||
|
||||
return domains
|
||||
}
|
||||
|
||||
func containsSAN(domains []string, sanName string) bool {
|
||||
for _, existingName := range domains {
|
||||
if existingName == sanName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func GeneratePemCert(privateKey *rsa.PrivateKey, domain string, extensions []pkix.Extension) ([]byte, error) {
|
||||
derBytes, err := generateDerCert(privateKey, time.Time{}, domain, extensions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}), nil
|
||||
}
|
||||
|
||||
func generateDerCert(privateKey *rsa.PrivateKey, expiration time.Time, domain string, extensions []pkix.Extension) ([]byte, error) {
|
||||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
||||
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if expiration.IsZero() {
|
||||
expiration = time.Now().AddDate(1, 0, 0)
|
||||
}
|
||||
|
||||
template := x509.Certificate{
|
||||
SerialNumber: serialNumber,
|
||||
Subject: pkix.Name{
|
||||
CommonName: "ACME Challenge TEMP",
|
||||
},
|
||||
NotBefore: time.Now(),
|
||||
NotAfter: expiration,
|
||||
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment,
|
||||
BasicConstraintsValid: true,
|
||||
ExtraExtensions: extensions,
|
||||
}
|
||||
|
||||
// handling SAN filling as type suspected
|
||||
if ip := net.ParseIP(domain); ip != nil {
|
||||
template.IPAddresses = []net.IP{ip}
|
||||
} else {
|
||||
template.DNSNames = []string{domain}
|
||||
}
|
||||
|
||||
return x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
|
||||
}
|
177
certcrypto/crypto_test.go
Normal file
177
certcrypto/crypto_test.go
Normal file
|
@ -0,0 +1,177 @@
|
|||
package certcrypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/pem"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGeneratePrivateKey(t *testing.T) {
|
||||
key, err := GeneratePrivateKey(RSA2048)
|
||||
require.NoError(t, err, "Error generating private key")
|
||||
|
||||
assert.NotNil(t, key)
|
||||
}
|
||||
|
||||
func TestGenerateCSR(t *testing.T) {
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err, "Error generating private key")
|
||||
|
||||
type expected struct {
|
||||
len int
|
||||
error bool
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
privateKey crypto.PrivateKey
|
||||
domain string
|
||||
san []string
|
||||
mustStaple bool
|
||||
expected expected
|
||||
}{
|
||||
{
|
||||
desc: "without SAN",
|
||||
privateKey: privateKey,
|
||||
domain: "lego.acme",
|
||||
mustStaple: true,
|
||||
expected: expected{len: 245},
|
||||
},
|
||||
{
|
||||
desc: "without SAN",
|
||||
privateKey: privateKey,
|
||||
domain: "lego.acme",
|
||||
san: []string{},
|
||||
mustStaple: true,
|
||||
expected: expected{len: 245},
|
||||
},
|
||||
{
|
||||
desc: "with SAN",
|
||||
privateKey: privateKey,
|
||||
domain: "lego.acme",
|
||||
san: []string{"a.lego.acme", "b.lego.acme", "c.lego.acme"},
|
||||
mustStaple: true,
|
||||
expected: expected{len: 296},
|
||||
},
|
||||
{
|
||||
desc: "no domain",
|
||||
privateKey: privateKey,
|
||||
domain: "",
|
||||
mustStaple: true,
|
||||
expected: expected{len: 225},
|
||||
},
|
||||
{
|
||||
desc: "no domain with SAN",
|
||||
privateKey: privateKey,
|
||||
domain: "",
|
||||
san: []string{"a.lego.acme", "b.lego.acme", "c.lego.acme"},
|
||||
mustStaple: true,
|
||||
expected: expected{len: 276},
|
||||
},
|
||||
{
|
||||
desc: "private key nil",
|
||||
privateKey: nil,
|
||||
domain: "fizz.buzz",
|
||||
mustStaple: true,
|
||||
expected: expected{error: true},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
csr, err := GenerateCSR(test.privateKey, test.domain, test.san, test.mustStaple)
|
||||
|
||||
if test.expected.error {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err, "Error generating CSR")
|
||||
|
||||
assert.NotEmpty(t, csr)
|
||||
assert.Len(t, csr, test.expected.len)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPEMEncode(t *testing.T) {
|
||||
buf := bytes.NewBufferString("TestingRSAIsSoMuchFun")
|
||||
|
||||
reader := MockRandReader{b: buf}
|
||||
key, err := rsa.GenerateKey(reader, 32)
|
||||
require.NoError(t, err, "Error generating private key")
|
||||
|
||||
data := PEMEncode(key)
|
||||
require.NotNil(t, data)
|
||||
|
||||
exp := regexp.MustCompile(`^-----BEGIN RSA PRIVATE KEY-----\s+\S{60,}\s+-----END RSA PRIVATE KEY-----\s+`)
|
||||
assert.Regexp(t, exp, string(data))
|
||||
}
|
||||
|
||||
func TestParsePEMCertificate(t *testing.T) {
|
||||
privateKey, err := GeneratePrivateKey(RSA2048)
|
||||
require.NoError(t, err, "Error generating private key")
|
||||
|
||||
expiration := time.Now().Add(365).Round(time.Second)
|
||||
certBytes, err := generateDerCert(privateKey.(*rsa.PrivateKey), expiration, "test.com", nil)
|
||||
require.NoError(t, err, "Error generating cert")
|
||||
|
||||
buf := bytes.NewBufferString("TestingRSAIsSoMuchFun")
|
||||
|
||||
// Some random string should return an error.
|
||||
cert, err := ParsePEMCertificate(buf.Bytes())
|
||||
require.Errorf(t, err, "returned %v", cert)
|
||||
|
||||
// A DER encoded certificate should return an error.
|
||||
_, err = ParsePEMCertificate(certBytes)
|
||||
require.Error(t, err, "Expected to return an error for DER certificates")
|
||||
|
||||
// A PEM encoded certificate should work ok.
|
||||
pemCert := PEMEncode(DERCertificateBytes(certBytes))
|
||||
cert, err = ParsePEMCertificate(pemCert)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, expiration.UTC(), cert.NotAfter)
|
||||
}
|
||||
|
||||
func TestParsePEMPrivateKey(t *testing.T) {
|
||||
privateKey, err := GeneratePrivateKey(RSA2048)
|
||||
require.NoError(t, err, "Error generating private key")
|
||||
|
||||
pemPrivateKey := PEMEncode(privateKey)
|
||||
|
||||
// Decoding a key should work and create an identical key to the original
|
||||
decoded, err := ParsePEMPrivateKey(pemPrivateKey)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, decoded, privateKey)
|
||||
|
||||
// Decoding a PEM block that doesn't contain a private key should error
|
||||
_, err = ParsePEMPrivateKey(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE"}))
|
||||
require.Errorf(t, err, "Expected to return an error for non-private key input")
|
||||
|
||||
// Decoding a PEM block that doesn't actually contain a key should error
|
||||
_, err = ParsePEMPrivateKey(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY"}))
|
||||
require.Errorf(t, err, "Expected to return an error for empty input")
|
||||
|
||||
// Decoding non-PEM input should return an error
|
||||
_, err = ParsePEMPrivateKey([]byte("This is not PEM"))
|
||||
require.Errorf(t, err, "Expected to return an error for non-PEM input")
|
||||
}
|
||||
|
||||
type MockRandReader struct {
|
||||
b *bytes.Buffer
|
||||
}
|
||||
|
||||
func (r MockRandReader) Read(p []byte) (int, error) {
|
||||
return r.b.Read(p)
|
||||
}
|
81
certificate/authorization.go
Normal file
81
certificate/authorization.go
Normal file
|
@ -0,0 +1,81 @@
|
|||
package certificate
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
const (
|
||||
// overallRequestLimit is the overall number of request per second
|
||||
// limited on the "new-reg", "new-authz" and "new-cert" endpoints.
|
||||
// From the documentation the limitation is 20 requests per second,
|
||||
// but using 20 as value doesn't work but 18 do.
|
||||
overallRequestLimit = 18
|
||||
)
|
||||
|
||||
func (c *Certifier) getAuthorizations(order acme.ExtendedOrder) ([]acme.Authorization, error) {
|
||||
resc, errc := make(chan acme.Authorization), make(chan domainError)
|
||||
|
||||
delay := time.Second / overallRequestLimit
|
||||
|
||||
for _, authzURL := range order.Authorizations {
|
||||
time.Sleep(delay)
|
||||
|
||||
go func(authzURL string) {
|
||||
authz, err := c.core.Authorizations.Get(authzURL)
|
||||
if err != nil {
|
||||
errc <- domainError{Domain: authz.Identifier.Value, Error: err}
|
||||
return
|
||||
}
|
||||
|
||||
resc <- authz
|
||||
}(authzURL)
|
||||
}
|
||||
|
||||
var responses []acme.Authorization
|
||||
failures := make(obtainError)
|
||||
for i := 0; i < len(order.Authorizations); i++ {
|
||||
select {
|
||||
case res := <-resc:
|
||||
responses = append(responses, res)
|
||||
case err := <-errc:
|
||||
failures[err.Domain] = err.Error
|
||||
}
|
||||
}
|
||||
|
||||
for i, auth := range order.Authorizations {
|
||||
log.Infof("[%s] AuthURL: %s", order.Identifiers[i].Value, auth)
|
||||
}
|
||||
|
||||
close(resc)
|
||||
close(errc)
|
||||
|
||||
// be careful to not return an empty failures map;
|
||||
// even if empty, they become non-nil error values
|
||||
if len(failures) > 0 {
|
||||
return responses, failures
|
||||
}
|
||||
return responses, nil
|
||||
}
|
||||
|
||||
func (c *Certifier) deactivateAuthorizations(order acme.ExtendedOrder, force bool) {
|
||||
for _, authzURL := range order.Authorizations {
|
||||
auth, err := c.core.Authorizations.Get(authzURL)
|
||||
if err != nil {
|
||||
log.Infof("Unable to get the authorization for: %s", authzURL)
|
||||
continue
|
||||
}
|
||||
|
||||
if auth.Status == acme.StatusValid && !force {
|
||||
log.Infof("Skipping deactivating of valid auth: %s", authzURL)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Infof("Deactivating auth: %s", authzURL)
|
||||
if c.core.Authorizations.Deactivate(authzURL) != nil {
|
||||
log.Infof("Unable to deactivate the authorization: %s", authzURL)
|
||||
}
|
||||
}
|
||||
}
|
662
certificate/certificates.go
Normal file
662
certificate/certificates.go
Normal file
|
@ -0,0 +1,662 @@
|
|||
package certificate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/go-acme/lego/v4/platform/wait"
|
||||
"golang.org/x/crypto/ocsp"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
// maxBodySize is the maximum size of body that we will read.
|
||||
const maxBodySize = 1024 * 1024
|
||||
|
||||
// Resource represents a CA issued certificate.
|
||||
// PrivateKey, Certificate and IssuerCertificate are all
|
||||
// already PEM encoded and can be directly written to disk.
|
||||
// Certificate may be a certificate bundle,
|
||||
// depending on the options supplied to create it.
|
||||
type Resource struct {
|
||||
Domain string `json:"domain"`
|
||||
CertURL string `json:"certUrl"`
|
||||
CertStableURL string `json:"certStableUrl"`
|
||||
PrivateKey []byte `json:"-"`
|
||||
Certificate []byte `json:"-"`
|
||||
IssuerCertificate []byte `json:"-"`
|
||||
CSR []byte `json:"-"`
|
||||
}
|
||||
|
||||
// ObtainRequest The request to obtain certificate.
|
||||
//
|
||||
// The first domain in domains is used for the CommonName field of the certificate,
|
||||
// all other domains are added using the Subject Alternate Names extension.
|
||||
//
|
||||
// A new private key is generated for every invocation of the function Obtain.
|
||||
// If you do not want that you can supply your own private key in the privateKey parameter.
|
||||
// If this parameter is non-nil it will be used instead of generating a new one.
|
||||
//
|
||||
// If `Bundle` is true, the `[]byte` contains both the issuer certificate and your issued certificate as a bundle.
|
||||
//
|
||||
// If `AlwaysDeactivateAuthorizations` is true, the authorizations are also relinquished if the obtain request was successful.
|
||||
// See https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.2.
|
||||
type ObtainRequest struct {
|
||||
Domains []string
|
||||
PrivateKey crypto.PrivateKey
|
||||
MustStaple bool
|
||||
|
||||
NotBefore time.Time
|
||||
NotAfter time.Time
|
||||
Bundle bool
|
||||
PreferredChain string
|
||||
AlwaysDeactivateAuthorizations bool
|
||||
}
|
||||
|
||||
// ObtainForCSRRequest The request to obtain a certificate matching the CSR passed into it.
|
||||
//
|
||||
// If `Bundle` is true, the `[]byte` contains both the issuer certificate and your issued certificate as a bundle.
|
||||
//
|
||||
// If `AlwaysDeactivateAuthorizations` is true, the authorizations are also relinquished if the obtain request was successful.
|
||||
// See https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.2.
|
||||
type ObtainForCSRRequest struct {
|
||||
CSR *x509.CertificateRequest
|
||||
|
||||
NotBefore time.Time
|
||||
NotAfter time.Time
|
||||
Bundle bool
|
||||
PreferredChain string
|
||||
AlwaysDeactivateAuthorizations bool
|
||||
}
|
||||
|
||||
type resolver interface {
|
||||
Solve(authorizations []acme.Authorization) error
|
||||
}
|
||||
|
||||
type CertifierOptions struct {
|
||||
KeyType certcrypto.KeyType
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Certifier A service to obtain/renew/revoke certificates.
|
||||
type Certifier struct {
|
||||
core *api.Core
|
||||
resolver resolver
|
||||
options CertifierOptions
|
||||
}
|
||||
|
||||
// NewCertifier creates a Certifier.
|
||||
func NewCertifier(core *api.Core, resolver resolver, options CertifierOptions) *Certifier {
|
||||
return &Certifier{
|
||||
core: core,
|
||||
resolver: resolver,
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
// Obtain tries to obtain a single certificate using all domains passed into it.
|
||||
//
|
||||
// This function will never return a partial certificate.
|
||||
// If one domain in the list fails, the whole certificate will fail.
|
||||
func (c *Certifier) Obtain(request ObtainRequest) (*Resource, error) {
|
||||
if len(request.Domains) == 0 {
|
||||
return nil, errors.New("no domains to obtain a certificate for")
|
||||
}
|
||||
|
||||
domains := sanitizeDomain(request.Domains)
|
||||
|
||||
if request.Bundle {
|
||||
log.Infof("[%s] acme: Obtaining bundled SAN certificate", strings.Join(domains, ", "))
|
||||
} else {
|
||||
log.Infof("[%s] acme: Obtaining SAN certificate", strings.Join(domains, ", "))
|
||||
}
|
||||
|
||||
orderOpts := &api.OrderOptions{
|
||||
NotBefore: request.NotBefore,
|
||||
NotAfter: request.NotAfter,
|
||||
}
|
||||
|
||||
order, err := c.core.Orders.NewWithOptions(domains, orderOpts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
authz, err := c.getAuthorizations(order)
|
||||
if err != nil {
|
||||
// If any challenge fails, return. Do not generate partial SAN certificates.
|
||||
c.deactivateAuthorizations(order, request.AlwaysDeactivateAuthorizations)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.resolver.Solve(authz)
|
||||
if err != nil {
|
||||
// If any challenge fails, return. Do not generate partial SAN certificates.
|
||||
c.deactivateAuthorizations(order, request.AlwaysDeactivateAuthorizations)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", "))
|
||||
|
||||
failures := make(obtainError)
|
||||
cert, err := c.getForOrder(domains, order, request.Bundle, request.PrivateKey, request.MustStaple, request.PreferredChain)
|
||||
if err != nil {
|
||||
for _, auth := range authz {
|
||||
failures[challenge.GetTargetedDomain(auth)] = err
|
||||
}
|
||||
}
|
||||
|
||||
if request.AlwaysDeactivateAuthorizations {
|
||||
c.deactivateAuthorizations(order, true)
|
||||
}
|
||||
|
||||
// Do not return an empty failures map, because
|
||||
// it would still be a non-nil error value
|
||||
if len(failures) > 0 {
|
||||
return cert, failures
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
// ObtainForCSR tries to obtain a certificate matching the CSR passed into it.
|
||||
//
|
||||
// The domains are inferred from the CommonName and SubjectAltNames, if any.
|
||||
// The private key for this CSR is not required.
|
||||
//
|
||||
// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle.
|
||||
//
|
||||
// This function will never return a partial certificate.
|
||||
// If one domain in the list fails, the whole certificate will fail.
|
||||
func (c *Certifier) ObtainForCSR(request ObtainForCSRRequest) (*Resource, error) {
|
||||
if request.CSR == nil {
|
||||
return nil, errors.New("cannot obtain resource for CSR: CSR is missing")
|
||||
}
|
||||
|
||||
// figure out what domains it concerns
|
||||
// start with the common name
|
||||
domains := certcrypto.ExtractDomainsCSR(request.CSR)
|
||||
|
||||
if request.Bundle {
|
||||
log.Infof("[%s] acme: Obtaining bundled SAN certificate given a CSR", strings.Join(domains, ", "))
|
||||
} else {
|
||||
log.Infof("[%s] acme: Obtaining SAN certificate given a CSR", strings.Join(domains, ", "))
|
||||
}
|
||||
|
||||
orderOpts := &api.OrderOptions{
|
||||
NotBefore: request.NotBefore,
|
||||
NotAfter: request.NotAfter,
|
||||
}
|
||||
|
||||
order, err := c.core.Orders.NewWithOptions(domains, orderOpts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
authz, err := c.getAuthorizations(order)
|
||||
if err != nil {
|
||||
// If any challenge fails, return. Do not generate partial SAN certificates.
|
||||
c.deactivateAuthorizations(order, request.AlwaysDeactivateAuthorizations)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.resolver.Solve(authz)
|
||||
if err != nil {
|
||||
// If any challenge fails, return. Do not generate partial SAN certificates.
|
||||
c.deactivateAuthorizations(order, request.AlwaysDeactivateAuthorizations)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", "))
|
||||
|
||||
failures := make(obtainError)
|
||||
cert, err := c.getForCSR(domains, order, request.Bundle, request.CSR.Raw, nil, request.PreferredChain)
|
||||
if err != nil {
|
||||
for _, auth := range authz {
|
||||
failures[challenge.GetTargetedDomain(auth)] = err
|
||||
}
|
||||
}
|
||||
|
||||
if request.AlwaysDeactivateAuthorizations {
|
||||
c.deactivateAuthorizations(order, true)
|
||||
}
|
||||
|
||||
if cert != nil {
|
||||
// Add the CSR to the certificate so that it can be used for renewals.
|
||||
cert.CSR = certcrypto.PEMEncode(request.CSR)
|
||||
}
|
||||
|
||||
// Do not return an empty failures map,
|
||||
// because it would still be a non-nil error value
|
||||
if len(failures) > 0 {
|
||||
return cert, failures
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
func (c *Certifier) getForOrder(domains []string, order acme.ExtendedOrder, bundle bool, privateKey crypto.PrivateKey, mustStaple bool, preferredChain string) (*Resource, error) {
|
||||
if privateKey == nil {
|
||||
var err error
|
||||
privateKey, err = certcrypto.GeneratePrivateKey(c.options.KeyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Determine certificate name(s) based on the authorization resources
|
||||
commonName := domains[0]
|
||||
|
||||
// RFC8555 Section 7.4 "Applying for Certificate Issuance"
|
||||
// https://www.rfc-editor.org/rfc/rfc8555.html#section-7.4
|
||||
// says:
|
||||
// Clients SHOULD NOT make any assumptions about the sort order of
|
||||
// "identifiers" or "authorizations" elements in the returned order
|
||||
// object.
|
||||
san := []string{commonName}
|
||||
for _, auth := range order.Identifiers {
|
||||
if auth.Value != commonName {
|
||||
san = append(san, auth.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: should the CSR be customizable?
|
||||
csr, err := certcrypto.GenerateCSR(privateKey, commonName, san, mustStaple)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return c.getForCSR(domains, order, bundle, csr, certcrypto.PEMEncode(privateKey), preferredChain)
|
||||
}
|
||||
|
||||
func (c *Certifier) getForCSR(domains []string, order acme.ExtendedOrder, bundle bool, csr, privateKeyPem []byte, preferredChain string) (*Resource, error) {
|
||||
respOrder, err := c.core.Orders.UpdateForCSR(order.Finalize, csr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
commonName := domains[0]
|
||||
certRes := &Resource{
|
||||
Domain: commonName,
|
||||
CertURL: respOrder.Certificate,
|
||||
PrivateKey: privateKeyPem,
|
||||
}
|
||||
|
||||
if respOrder.Status == acme.StatusValid {
|
||||
// if the certificate is available right away, short cut!
|
||||
ok, errR := c.checkResponse(respOrder, certRes, bundle, preferredChain)
|
||||
if errR != nil {
|
||||
return nil, errR
|
||||
}
|
||||
|
||||
if ok {
|
||||
return certRes, nil
|
||||
}
|
||||
}
|
||||
|
||||
timeout := c.options.Timeout
|
||||
if c.options.Timeout <= 0 {
|
||||
timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
err = wait.For("certificate", timeout, timeout/60, func() (bool, error) {
|
||||
ord, errW := c.core.Orders.Get(order.Location)
|
||||
if errW != nil {
|
||||
return false, errW
|
||||
}
|
||||
|
||||
done, errW := c.checkResponse(ord, certRes, bundle, preferredChain)
|
||||
if errW != nil {
|
||||
return false, errW
|
||||
}
|
||||
|
||||
return done, nil
|
||||
})
|
||||
|
||||
return certRes, err
|
||||
}
|
||||
|
||||
// checkResponse checks to see if the certificate is ready and a link is contained in the response.
|
||||
//
|
||||
// If so, loads it into certRes and returns true.
|
||||
// If the cert is not yet ready, it returns false.
|
||||
//
|
||||
// The certRes input should already have the Domain (common name) field populated.
|
||||
//
|
||||
// If bundle is true, the certificate will be bundled with the issuer's cert.
|
||||
func (c *Certifier) checkResponse(order acme.ExtendedOrder, certRes *Resource, bundle bool, preferredChain string) (bool, error) {
|
||||
valid, err := checkOrderStatus(order)
|
||||
if err != nil || !valid {
|
||||
return valid, err
|
||||
}
|
||||
|
||||
certs, err := c.core.Certificates.GetAll(order.Certificate, bundle)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Set the default certificate
|
||||
certRes.IssuerCertificate = certs[order.Certificate].Issuer
|
||||
certRes.Certificate = certs[order.Certificate].Cert
|
||||
certRes.CertURL = order.Certificate
|
||||
certRes.CertStableURL = order.Certificate
|
||||
|
||||
if preferredChain == "" {
|
||||
log.Infof("[%s] Server responded with a certificate.", certRes.Domain)
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
for link, cert := range certs {
|
||||
ok, err := hasPreferredChain(cert.Issuer, preferredChain)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if ok {
|
||||
log.Infof("[%s] Server responded with a certificate for the preferred certificate chains %q.", certRes.Domain, preferredChain)
|
||||
|
||||
certRes.IssuerCertificate = cert.Issuer
|
||||
certRes.Certificate = cert.Cert
|
||||
certRes.CertURL = link
|
||||
certRes.CertStableURL = link
|
||||
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("lego has been configured to prefer certificate chains with issuer %q, but no chain from the CA matched this issuer. Using the default certificate chain instead.", preferredChain)
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Revoke takes a PEM encoded certificate or bundle and tries to revoke it at the CA.
|
||||
func (c *Certifier) Revoke(cert []byte) error {
|
||||
return c.RevokeWithReason(cert, nil)
|
||||
}
|
||||
|
||||
// RevokeWithReason takes a PEM encoded certificate or bundle and tries to revoke it at the CA.
|
||||
func (c *Certifier) RevokeWithReason(cert []byte, reason *uint) error {
|
||||
certificates, err := certcrypto.ParsePEMBundle(cert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
x509Cert := certificates[0]
|
||||
if x509Cert.IsCA {
|
||||
return errors.New("certificate bundle starts with a CA certificate")
|
||||
}
|
||||
|
||||
revokeMsg := acme.RevokeCertMessage{
|
||||
Certificate: base64.RawURLEncoding.EncodeToString(x509Cert.Raw),
|
||||
Reason: reason,
|
||||
}
|
||||
|
||||
return c.core.Certificates.Revoke(revokeMsg)
|
||||
}
|
||||
|
||||
// RenewOptions options used by Certifier.RenewWithOptions.
|
||||
type RenewOptions struct {
|
||||
NotBefore time.Time
|
||||
NotAfter time.Time
|
||||
// If true, the []byte contains both the issuer certificate and your issued certificate as a bundle.
|
||||
Bundle bool
|
||||
PreferredChain string
|
||||
AlwaysDeactivateAuthorizations bool
|
||||
// Not supported for CSR request.
|
||||
MustStaple bool
|
||||
}
|
||||
|
||||
// Renew takes a Resource and tries to renew the certificate.
|
||||
//
|
||||
// If the renewal process succeeds, the new certificate will be returned in a new CertResource.
|
||||
// Please be aware that this function will return a new certificate in ANY case that is not an error.
|
||||
// If the server does not provide us with a new cert on a GET request to the CertURL
|
||||
// this function will start a new-cert flow where a new certificate gets generated.
|
||||
//
|
||||
// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle.
|
||||
//
|
||||
// For private key reuse the PrivateKey property of the passed in Resource should be non-nil.
|
||||
// Deprecated: use RenewWithOptions instead.
|
||||
func (c *Certifier) Renew(certRes Resource, bundle, mustStaple bool, preferredChain string) (*Resource, error) {
|
||||
return c.RenewWithOptions(certRes, &RenewOptions{
|
||||
Bundle: bundle,
|
||||
PreferredChain: preferredChain,
|
||||
MustStaple: mustStaple,
|
||||
})
|
||||
}
|
||||
|
||||
// RenewWithOptions takes a Resource and tries to renew the certificate.
|
||||
//
|
||||
// If the renewal process succeeds, the new certificate will be returned in a new CertResource.
|
||||
// Please be aware that this function will return a new certificate in ANY case that is not an error.
|
||||
// If the server does not provide us with a new cert on a GET request to the CertURL
|
||||
// this function will start a new-cert flow where a new certificate gets generated.
|
||||
//
|
||||
// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle.
|
||||
//
|
||||
// For private key reuse the PrivateKey property of the passed in Resource should be non-nil.
|
||||
func (c *Certifier) RenewWithOptions(certRes Resource, options *RenewOptions) (*Resource, error) {
|
||||
// Input certificate is PEM encoded.
|
||||
// Decode it here as we may need the decoded cert later on in the renewal process.
|
||||
// The input may be a bundle or a single certificate.
|
||||
certificates, err := certcrypto.ParsePEMBundle(certRes.Certificate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
x509Cert := certificates[0]
|
||||
if x509Cert.IsCA {
|
||||
return nil, fmt.Errorf("[%s] Certificate bundle starts with a CA certificate", certRes.Domain)
|
||||
}
|
||||
|
||||
// This is just meant to be informal for the user.
|
||||
timeLeft := x509Cert.NotAfter.Sub(time.Now().UTC())
|
||||
log.Infof("[%s] acme: Trying renewal with %d hours remaining", certRes.Domain, int(timeLeft.Hours()))
|
||||
|
||||
// We always need to request a new certificate to renew.
|
||||
// Start by checking to see if the certificate was based off a CSR,
|
||||
// and use that if it's defined.
|
||||
if len(certRes.CSR) > 0 {
|
||||
csr, errP := certcrypto.PemDecodeTox509CSR(certRes.CSR)
|
||||
if errP != nil {
|
||||
return nil, errP
|
||||
}
|
||||
|
||||
request := ObtainForCSRRequest{CSR: csr}
|
||||
|
||||
if options != nil {
|
||||
request.NotBefore = options.NotBefore
|
||||
request.NotAfter = options.NotAfter
|
||||
request.Bundle = options.Bundle
|
||||
request.PreferredChain = options.PreferredChain
|
||||
request.AlwaysDeactivateAuthorizations = options.AlwaysDeactivateAuthorizations
|
||||
}
|
||||
|
||||
return c.ObtainForCSR(request)
|
||||
}
|
||||
|
||||
var privateKey crypto.PrivateKey
|
||||
if certRes.PrivateKey != nil {
|
||||
privateKey, err = certcrypto.ParsePEMPrivateKey(certRes.PrivateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
request := ObtainRequest{
|
||||
Domains: certcrypto.ExtractDomains(x509Cert),
|
||||
PrivateKey: privateKey,
|
||||
}
|
||||
|
||||
if options != nil {
|
||||
request.MustStaple = options.MustStaple
|
||||
request.NotBefore = options.NotBefore
|
||||
request.NotAfter = options.NotAfter
|
||||
request.Bundle = options.Bundle
|
||||
request.PreferredChain = options.PreferredChain
|
||||
request.AlwaysDeactivateAuthorizations = options.AlwaysDeactivateAuthorizations
|
||||
}
|
||||
|
||||
return c.Obtain(request)
|
||||
}
|
||||
|
||||
// GetOCSP takes a PEM encoded cert or cert bundle returning the raw OCSP response,
|
||||
// the parsed response, and an error, if any.
|
||||
//
|
||||
// The returned []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.
|
||||
//
|
||||
// If the []byte and/or ocsp.Response return values are nil, the OCSP status may be assumed OCSPUnknown.
|
||||
func (c *Certifier) GetOCSP(bundle []byte) ([]byte, *ocsp.Response, error) {
|
||||
certificates, err := certcrypto.ParsePEMBundle(bundle)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// We expect the certificate slice to be ordered downwards the chain.
|
||||
// SRV CRT -> CA. We need to pull the leaf and issuer certs out of it,
|
||||
// which should always be the first two certificates.
|
||||
// If there's no OCSP server listed in the leaf cert, there's nothing to do.
|
||||
// And if we have only one certificate so far, we need to get the issuer cert.
|
||||
|
||||
issuedCert := certificates[0]
|
||||
|
||||
if len(issuedCert.OCSPServer) == 0 {
|
||||
return nil, nil, errors.New("no OCSP server specified in cert")
|
||||
}
|
||||
|
||||
if len(certificates) == 1 {
|
||||
// TODO: build fallback. If this fails, check the remaining array entries.
|
||||
if len(issuedCert.IssuingCertificateURL) == 0 {
|
||||
return nil, nil, errors.New("no issuing certificate URL")
|
||||
}
|
||||
|
||||
resp, errC := c.core.HTTPClient.Get(issuedCert.IssuingCertificateURL[0])
|
||||
if errC != nil {
|
||||
return nil, nil, errC
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
issuerBytes, errC := io.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize))
|
||||
if errC != nil {
|
||||
return nil, nil, errC
|
||||
}
|
||||
|
||||
issuerCert, errC := x509.ParseCertificate(issuerBytes)
|
||||
if errC != nil {
|
||||
return nil, nil, errC
|
||||
}
|
||||
|
||||
// Insert it into the slice on position 0
|
||||
// We want it ordered right SRV CRT -> CA
|
||||
certificates = append(certificates, issuerCert)
|
||||
}
|
||||
|
||||
issuerCert := certificates[1]
|
||||
|
||||
// Finally kick off the OCSP request.
|
||||
ocspReq, err := ocsp.CreateRequest(issuedCert, issuerCert, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
resp, err := c.core.HTTPClient.Post(issuedCert.OCSPServer[0], "application/ocsp-request", bytes.NewReader(ocspReq))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
ocspResBytes, err := io.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
ocspRes, err := ocsp.ParseResponse(ocspResBytes, issuerCert)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return ocspResBytes, ocspRes, nil
|
||||
}
|
||||
|
||||
// Get attempts to fetch the certificate at the supplied URL.
|
||||
// The URL is the same as what would normally be supplied at the Resource's CertURL.
|
||||
//
|
||||
// The returned Resource will not have the PrivateKey and CSR fields populated as these will not be available.
|
||||
//
|
||||
// If bundle is true, the Certificate field in the returned Resource includes the issuer certificate.
|
||||
func (c *Certifier) Get(url string, bundle bool) (*Resource, error) {
|
||||
cert, issuer, err := c.core.Certificates.Get(url, bundle)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Parse the returned cert bundle so that we can grab the domain from the common name.
|
||||
x509Certs, err := certcrypto.ParsePEMBundle(cert)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Resource{
|
||||
Domain: x509Certs[0].Subject.CommonName,
|
||||
Certificate: cert,
|
||||
IssuerCertificate: issuer,
|
||||
CertURL: url,
|
||||
CertStableURL: url,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func hasPreferredChain(issuer []byte, preferredChain string) (bool, error) {
|
||||
certs, err := certcrypto.ParsePEMBundle(issuer)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
topCert := certs[len(certs)-1]
|
||||
|
||||
if topCert.Issuer.CommonName == preferredChain {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func checkOrderStatus(order acme.ExtendedOrder) (bool, error) {
|
||||
switch order.Status {
|
||||
case acme.StatusValid:
|
||||
return true, nil
|
||||
case acme.StatusInvalid:
|
||||
return false, order.Error
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
// https://www.rfc-editor.org/rfc/rfc8555.html#section-7.1.4
|
||||
// The domain name MUST be encoded in the form in which it would appear in a certificate.
|
||||
// That is, it MUST be encoded according to the rules in Section 7 of [RFC5280].
|
||||
//
|
||||
// https://www.rfc-editor.org/rfc/rfc5280.html#section-7
|
||||
func sanitizeDomain(domains []string) []string {
|
||||
var sanitizedDomains []string
|
||||
for _, domain := range domains {
|
||||
sanitizedDomain, err := idna.ToASCII(domain)
|
||||
if err != nil {
|
||||
log.Infof("skip domain %q: unable to sanitize (punnycode): %v", domain, err)
|
||||
} else {
|
||||
sanitizedDomains = append(sanitizedDomains, sanitizedDomain)
|
||||
}
|
||||
}
|
||||
return sanitizedDomains
|
||||
}
|
398
certificate/certificates_test.go
Normal file
398
certificate/certificates_test.go
Normal file
|
@ -0,0 +1,398 @@
|
|||
package certificate
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const certResponseNoBundleMock = `-----BEGIN CERTIFICATE-----
|
||||
MIIDEDCCAfigAwIBAgIHPhckqW5fPDANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQD
|
||||
Ex1QZWJibGUgSW50ZXJtZWRpYXRlIENBIDM5NWU2MTAeFw0xODExMDcxNzQ2NTZa
|
||||
Fw0yMzExMDcxNzQ2NTZaMBMxETAPBgNVBAMTCGFjbWUud3RmMIIBIjANBgkqhkiG
|
||||
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwtLNKvZXD20XPUQCWYSK9rUSKxD9Eb0c9fag
|
||||
bxOxOkLRTgL8LH6yln+bxc3MrHDou4PpDUdeo2CyOQu3CKsTS5mrH3NXYHu0H7p5
|
||||
y3riOJTHnfkGKLT9LciGz7GkXd62nvNP57bOf5Sk4P2M+Qbxd0hPTSfu52740LSy
|
||||
144cnxe2P1aDYehrEp6nYCESuyD/CtUHTo0qwJmzIy163Sp3rSs15BuCPyhySnE3
|
||||
BJ8Ggv+qC6D5I1932DfSqyQJ79iq/HRm0Fn84am3KwvRlUfWxabmsUGARXoqCgnE
|
||||
zcbJVOZKewv0zlQJpfac+b+Imj6Lvt1TGjIz2mVyefYgLx8gwwIDAQABo1QwUjAO
|
||||
BgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG
|
||||
A1UdEwEB/wQCMAAwEwYDVR0RBAwwCoIIYWNtZS53dGYwDQYJKoZIhvcNAQELBQAD
|
||||
ggEBABB/0iYhmfPSQot5RaeeovQnsqYjI5ryQK2cwzW6qcTJfv8N6+p6XkqF1+W4
|
||||
jXZjrQP8MvgO9KNWlvx12vhINE6wubk88L+2piAi5uS2QejmZbXpyYB9s+oPqlk9
|
||||
IDvfdlVYOqvYAhSx7ggGi+j73mjZVtjAavP6dKuu475ZCeq+NIC15RpbbikWKtYE
|
||||
HBJ7BW8XQKx67iHGx8ygHTDLbREL80Bck3oUm7wIYGMoNijD6RBl25p4gYl9dzOd
|
||||
TqGl5hW/1P5hMbgEzHbr4O3BfWqU2g7tV36TASy3jbC3ONFRNNYrpEZ1AL3+cUri
|
||||
OPPkKtAKAbQkKbUIfsHpBZjKZMU=
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
const certResponseMock = `-----BEGIN CERTIFICATE-----
|
||||
MIIDEDCCAfigAwIBAgIHPhckqW5fPDANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQD
|
||||
Ex1QZWJibGUgSW50ZXJtZWRpYXRlIENBIDM5NWU2MTAeFw0xODExMDcxNzQ2NTZa
|
||||
Fw0yMzExMDcxNzQ2NTZaMBMxETAPBgNVBAMTCGFjbWUud3RmMIIBIjANBgkqhkiG
|
||||
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwtLNKvZXD20XPUQCWYSK9rUSKxD9Eb0c9fag
|
||||
bxOxOkLRTgL8LH6yln+bxc3MrHDou4PpDUdeo2CyOQu3CKsTS5mrH3NXYHu0H7p5
|
||||
y3riOJTHnfkGKLT9LciGz7GkXd62nvNP57bOf5Sk4P2M+Qbxd0hPTSfu52740LSy
|
||||
144cnxe2P1aDYehrEp6nYCESuyD/CtUHTo0qwJmzIy163Sp3rSs15BuCPyhySnE3
|
||||
BJ8Ggv+qC6D5I1932DfSqyQJ79iq/HRm0Fn84am3KwvRlUfWxabmsUGARXoqCgnE
|
||||
zcbJVOZKewv0zlQJpfac+b+Imj6Lvt1TGjIz2mVyefYgLx8gwwIDAQABo1QwUjAO
|
||||
BgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwG
|
||||
A1UdEwEB/wQCMAAwEwYDVR0RBAwwCoIIYWNtZS53dGYwDQYJKoZIhvcNAQELBQAD
|
||||
ggEBABB/0iYhmfPSQot5RaeeovQnsqYjI5ryQK2cwzW6qcTJfv8N6+p6XkqF1+W4
|
||||
jXZjrQP8MvgO9KNWlvx12vhINE6wubk88L+2piAi5uS2QejmZbXpyYB9s+oPqlk9
|
||||
IDvfdlVYOqvYAhSx7ggGi+j73mjZVtjAavP6dKuu475ZCeq+NIC15RpbbikWKtYE
|
||||
HBJ7BW8XQKx67iHGx8ygHTDLbREL80Bck3oUm7wIYGMoNijD6RBl25p4gYl9dzOd
|
||||
TqGl5hW/1P5hMbgEzHbr4O3BfWqU2g7tV36TASy3jbC3ONFRNNYrpEZ1AL3+cUri
|
||||
OPPkKtAKAbQkKbUIfsHpBZjKZMU=
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE
|
||||
AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw
|
||||
NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl
|
||||
NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT
|
||||
SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh
|
||||
0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen
|
||||
SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx
|
||||
HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt
|
||||
D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu
|
||||
mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD
|
||||
AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA
|
||||
upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm
|
||||
iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd
|
||||
QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ
|
||||
wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv
|
||||
rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2
|
||||
7R4IbHGnj0BJA2vMYC4hSw==
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
const issuerMock = `-----BEGIN CERTIFICATE-----
|
||||
MIIDDDCCAfSgAwIBAgIIOV5hkYJx0JwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE
|
||||
AxMVUGViYmxlIFJvb3QgQ0EgNTBmZmJkMB4XDTE4MTEwNzE3NDY0N1oXDTQ4MTEw
|
||||
NzE3NDY0N1owKDEmMCQGA1UEAxMdUGViYmxlIEludGVybWVkaWF0ZSBDQSAzOTVl
|
||||
NjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacwXN4LmyRTgYS8TT
|
||||
SZYgz758npHiPTBDKgeN5WVmkkwW0TuN4W2zXhEmcM82uxOEjWS2drvK0+iJKneh
|
||||
0fQR8ZF35dIYFe8WXTg3kEmqcizSgh4LxlOntsXvatfX/6GU/ADo3xAFoBKCijen
|
||||
SRBIY65yq5m00cWx3RMIcQq1B0X8nJS0O1P7MYE/Vvidz5St/36RXVu1oWLeS5Fx
|
||||
HAezW0lqxEUzvC+uLTFWC6f/CilzmI7SsPAkZBk7dO5Qs0d7m/zWF588vlGS+0pt
|
||||
D1on+lU85Ma2zuAd0qmB6LY66N8pEKKtMk93wF/o4Z5i58ahbwNvTKAzz4JSRWSu
|
||||
mB9LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIChDAdBgNVHSUEFjAUBggrBgEFBQcD
|
||||
AQYIKwYBBQUHAwIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEA
|
||||
upU0DjzvIvoCOYKbq1RRN7rPdYad39mfjxgkeV0iOF5JoIdO6y1C7XAm9lT69Wjm
|
||||
iUPvnCTMDYft40N2SvmXuuMaPOm4zjNwn4K33jw5XBnpwxC7By/Y0oV+Sl10fBsd
|
||||
QqXC6H7LcSGkv+4eJbgY33P4uH5ZAy+2TkHUuZDkpufkAshzBust7nDAjfv3AIuQ
|
||||
wlPoyZfI11eqyiOqRzOq+B5dIBr1JzKnEzSL6n0JLNQiPO7iN03rud/wYD3gbmcv
|
||||
rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2
|
||||
7R4IbHGnj0BJA2vMYC4hSw==
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
const certResponseMock2 = `
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIFUzCCBDugAwIBAgISA/z9btaZCSo/qlVwmJrHpoyPMA0GCSqGSIb3DQEBCwUA
|
||||
MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD
|
||||
ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0yMDA3MjUwNjUxNDRaFw0y
|
||||
MDEwMjMwNjUxNDRaMBgxFjAUBgNVBAMTDW5hdHVyZS5nbG9iYWwwggEiMA0GCSqG
|
||||
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDN/PF8lWub3i+lO3CLl/HJAM86pQH9hWej
|
||||
Whci1PPNzKyEByJq2psNLCO1W1mXK3ClWSyifptCf7+AAFAOoBojPMwjaKMziw1M
|
||||
BxAQiX8MzZLv4Hr4Uk08cQX31QHiEpOv4pMHqB0UpodTYY10dZnDdyJHaGKzxfJh
|
||||
nQPYIVto+UegcVu9iZIDow7ugoT2Gh8nB8jOAc4wtBgmylgeAFmYR6QZ4PYSYFh0
|
||||
DLZGGB1WuU/4YC5OciwTDv5EiqP3KM3NdkmGhPY0A3jcTrjN+HhcE4pYBtG1wHi8
|
||||
PEuqqKyCLa3AjHq4WrZyCCkCMXPbIDS1Qt7botDmUZr/26xJZnl5AgMBAAGjggJj
|
||||
MIICXzAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF
|
||||
BwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFFm72Cv7LnjVhcLqUujrykUr70lF
|
||||
MB8GA1UdIwQYMBaAFKhKamMEfd265tE5t6ZFZe/zqOyhMG8GCCsGAQUFBwEBBGMw
|
||||
YTAuBggrBgEFBQcwAYYiaHR0cDovL29jc3AuaW50LXgzLmxldHNlbmNyeXB0Lm9y
|
||||
ZzAvBggrBgEFBQcwAoYjaHR0cDovL2NlcnQuaW50LXgzLmxldHNlbmNyeXB0Lm9y
|
||||
Zy8wGAYDVR0RBBEwD4INbmF0dXJlLmdsb2JhbDBMBgNVHSAERTBDMAgGBmeBDAEC
|
||||
ATA3BgsrBgEEAYLfEwEBATAoMCYGCCsGAQUFBwIBFhpodHRwOi8vY3BzLmxldHNl
|
||||
bmNyeXB0Lm9yZzCCAQUGCisGAQQB1nkCBAIEgfYEgfMA8QB3ALIeBcyLos2KIE6H
|
||||
ZvkruYolIGdr2vpw57JJUy3vi5BeAAABc4T006IAAAQDAEgwRgIhAPEEvCEMkekD
|
||||
8XLDaxHPnJ85UZL72JqGgNK+7I/NdFNuAiEA5D78b4V1YsD8wvWz/sk6Ks8VgjED
|
||||
eKGl/TyXwKEpzEIAdgBvU3asMfAxGdiZAKRRFf93FRwR2QLBACkGjbIImjfZEwAA
|
||||
AXOE9NPrAAAEAwBHMEUCIAu4YFfGZIN/P+0eRG0krSddHKCSf6rqr6aVqUWkJY3F
|
||||
AiEAz0HkTe0alED1gW9nEAJ1qqK1MLMjRM8SsUv9Is86+CwwDQYJKoZIhvcNAQEL
|
||||
BQADggEBAGriSVi9YuBnm50w84gjlinmeGdvxgugblIoEqKoXd3d5/zx0DvW9Tm6
|
||||
YGfXsvAJUSCag7dZ/s/PEu23jKNdFoaBmDaUHHKnUwbWWF7/ptYZ+YuDVGOJo8PL
|
||||
CULNfUMon20rPU9smzW4BFDBZ6KmX/r4Q8cQ7FLOqKdcng0yMcqIfq4cBxEvd0uQ
|
||||
pHR3AwCjAIGpV6Q9WHHiHx+SEd/Xc18Z5pXa9m3Rz4i6Mfv+AYLtnsZDxcH81cVM
|
||||
7rYp80vhXM9tFd4wyrqLuaVZgYD1ylxTYpTI7sijIq4Sl984f3IPA/olN+zK6E8d
|
||||
EbiufIcKeju/aSellDzzBabEo80YT4o=
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/
|
||||
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
|
||||
DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow
|
||||
PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD
|
||||
Ew5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
|
||||
AN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O
|
||||
rz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq
|
||||
OLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b
|
||||
xiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw
|
||||
7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD
|
||||
aeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV
|
||||
HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG
|
||||
SIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69
|
||||
ikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr
|
||||
AvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz
|
||||
R8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5
|
||||
JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo
|
||||
Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
const issuerMock2 = `-----BEGIN CERTIFICATE-----
|
||||
MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/
|
||||
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
|
||||
DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow
|
||||
PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD
|
||||
Ew5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
|
||||
AN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O
|
||||
rz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq
|
||||
OLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b
|
||||
xiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw
|
||||
7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD
|
||||
aeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV
|
||||
HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG
|
||||
SIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69
|
||||
ikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr
|
||||
AvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz
|
||||
R8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5
|
||||
JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo
|
||||
Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ
|
||||
-----END CERTIFICATE-----
|
||||
`
|
||||
|
||||
func Test_checkResponse(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, err := w.Write([]byte(certResponseMock))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
order := acme.ExtendedOrder{
|
||||
Order: acme.Order{
|
||||
Status: acme.StatusValid,
|
||||
Certificate: apiURL + "/certificate",
|
||||
},
|
||||
}
|
||||
certRes := &Resource{}
|
||||
|
||||
valid, err := certifier.checkResponse(order, certRes, true, "")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, valid)
|
||||
assert.NotNil(t, certRes)
|
||||
assert.Equal(t, "", certRes.Domain)
|
||||
assert.Contains(t, certRes.CertStableURL, "/certificate")
|
||||
assert.Contains(t, certRes.CertURL, "/certificate")
|
||||
assert.Nil(t, certRes.CSR)
|
||||
assert.Nil(t, certRes.PrivateKey)
|
||||
assert.Equal(t, certResponseMock, string(certRes.Certificate), "Certificate")
|
||||
assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate")
|
||||
}
|
||||
|
||||
func Test_checkResponse_issuerRelUp(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`)
|
||||
_, err := w.Write([]byte(certResponseMock))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
mux.HandleFunc("/issuer", func(w http.ResponseWriter, _ *http.Request) {
|
||||
p, _ := pem.Decode([]byte(issuerMock))
|
||||
_, err := w.Write(p.Bytes)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
order := acme.ExtendedOrder{
|
||||
Order: acme.Order{
|
||||
Status: acme.StatusValid,
|
||||
Certificate: apiURL + "/certificate",
|
||||
},
|
||||
}
|
||||
certRes := &Resource{}
|
||||
|
||||
valid, err := certifier.checkResponse(order, certRes, true, "")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, valid)
|
||||
assert.NotNil(t, certRes)
|
||||
assert.Equal(t, "", certRes.Domain)
|
||||
assert.Contains(t, certRes.CertStableURL, "/certificate")
|
||||
assert.Contains(t, certRes.CertURL, "/certificate")
|
||||
assert.Nil(t, certRes.CSR)
|
||||
assert.Nil(t, certRes.PrivateKey)
|
||||
assert.Equal(t, certResponseMock, string(certRes.Certificate), "Certificate")
|
||||
assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate")
|
||||
}
|
||||
|
||||
func Test_checkResponse_no_bundle(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, err := w.Write([]byte(certResponseMock))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
order := acme.ExtendedOrder{
|
||||
Order: acme.Order{
|
||||
Status: acme.StatusValid,
|
||||
Certificate: apiURL + "/certificate",
|
||||
},
|
||||
}
|
||||
certRes := &Resource{}
|
||||
|
||||
valid, err := certifier.checkResponse(order, certRes, false, "")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, valid)
|
||||
assert.NotNil(t, certRes)
|
||||
assert.Equal(t, "", certRes.Domain)
|
||||
assert.Contains(t, certRes.CertStableURL, "/certificate")
|
||||
assert.Contains(t, certRes.CertURL, "/certificate")
|
||||
assert.Nil(t, certRes.CSR)
|
||||
assert.Nil(t, certRes.PrivateKey)
|
||||
assert.Equal(t, certResponseNoBundleMock, string(certRes.Certificate), "Certificate")
|
||||
assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate")
|
||||
}
|
||||
|
||||
func Test_checkResponse_alternate(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Add("Link", fmt.Sprintf(`<%s/certificate/1>;title="foo";rel="alternate"`, apiURL))
|
||||
|
||||
_, err := w.Write([]byte(certResponseMock))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
mux.HandleFunc("/certificate/1", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, err := w.Write([]byte(certResponseMock2))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
order := acme.ExtendedOrder{
|
||||
Order: acme.Order{
|
||||
Status: acme.StatusValid,
|
||||
Certificate: apiURL + "/certificate",
|
||||
},
|
||||
}
|
||||
certRes := &Resource{
|
||||
Domain: "example.com",
|
||||
}
|
||||
|
||||
valid, err := certifier.checkResponse(order, certRes, true, "DST Root CA X3")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.True(t, valid)
|
||||
assert.NotNil(t, certRes)
|
||||
assert.Equal(t, "example.com", certRes.Domain)
|
||||
assert.Contains(t, certRes.CertStableURL, "/certificate/1")
|
||||
assert.Contains(t, certRes.CertURL, "/certificate/1")
|
||||
assert.Nil(t, certRes.CSR)
|
||||
assert.Nil(t, certRes.PrivateKey)
|
||||
assert.Equal(t, certResponseMock2, string(certRes.Certificate), "Certificate")
|
||||
assert.Equal(t, issuerMock2, string(certRes.IssuerCertificate), "IssuerCertificate")
|
||||
}
|
||||
|
||||
func Test_Get(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
mux.HandleFunc("/acme/cert/test-cert", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, err := w.Write([]byte(certResponseMock))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
certRes, err := certifier.Get(apiURL+"/acme/cert/test-cert", true)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotNil(t, certRes)
|
||||
assert.Equal(t, "acme.wtf", certRes.Domain)
|
||||
assert.Equal(t, apiURL+"/acme/cert/test-cert", certRes.CertStableURL)
|
||||
assert.Equal(t, apiURL+"/acme/cert/test-cert", certRes.CertURL)
|
||||
assert.Nil(t, certRes.CSR)
|
||||
assert.Nil(t, certRes.PrivateKey)
|
||||
assert.Equal(t, certResponseMock, string(certRes.Certificate), "Certificate")
|
||||
assert.Equal(t, issuerMock, string(certRes.IssuerCertificate), "IssuerCertificate")
|
||||
}
|
||||
|
||||
type resolverMock struct {
|
||||
error error
|
||||
}
|
||||
|
||||
func (r *resolverMock) Solve(_ []acme.Authorization) error {
|
||||
return r.error
|
||||
}
|
30
certificate/errors.go
Normal file
30
certificate/errors.go
Normal file
|
@ -0,0 +1,30 @@
|
|||
package certificate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// obtainError is returned when there are specific errors available per domain.
|
||||
type obtainError map[string]error
|
||||
|
||||
func (e obtainError) Error() string {
|
||||
buffer := bytes.NewBufferString("error: one or more domains had a problem:\n")
|
||||
|
||||
var domains []string
|
||||
for domain := range e {
|
||||
domains = append(domains, domain)
|
||||
}
|
||||
sort.Strings(domains)
|
||||
|
||||
for _, domain := range domains {
|
||||
_, _ = fmt.Fprintf(buffer, "[%s] %s\n", domain, e[domain])
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
type domainError struct {
|
||||
Domain string
|
||||
Error error
|
||||
}
|
204
certificate/renewal.go
Normal file
204
certificate/renewal.go
Normal file
|
@ -0,0 +1,204 @@
|
|||
package certificate
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/asn1"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
// RenewalInfoRequest contains the necessary renewal information.
|
||||
type RenewalInfoRequest struct {
|
||||
Cert *x509.Certificate
|
||||
Issuer *x509.Certificate
|
||||
// HashName must be the string representation of a crypto.Hash constant in the golang.org/x/crypto package (e.g. "SHA-256").
|
||||
// The correct value depends on the algorithm expected by the ACME server's ARI implementation.
|
||||
HashName string
|
||||
}
|
||||
|
||||
// RenewalInfoResponse is a wrapper around acme.RenewalInfoResponse that provides a method for determining when to renew a certificate.
|
||||
type RenewalInfoResponse struct {
|
||||
acme.RenewalInfoResponse
|
||||
}
|
||||
|
||||
// ShouldRenewAt determines the optimal renewal time based on the current time (UTC),renewal window suggest by ARI, and the client's willingness to sleep.
|
||||
// It returns a pointer to a time.Time value indicating when the renewal should be attempted or nil if deferred until the next normal wake time.
|
||||
// This method implements the RECOMMENDED algorithm described in draft-ietf-acme-ari.
|
||||
//
|
||||
// - (4.1-11. Getting Renewal Information) https://datatracker.ietf.org/doc/draft-ietf-acme-ari/
|
||||
func (r *RenewalInfoResponse) ShouldRenewAt(now time.Time, willingToSleep time.Duration) *time.Time {
|
||||
// Explicitly convert all times to UTC.
|
||||
now = now.UTC()
|
||||
start := r.SuggestedWindow.Start.UTC()
|
||||
end := r.SuggestedWindow.End.UTC()
|
||||
|
||||
// Select a uniform random time within the suggested window.
|
||||
window := end.Sub(start)
|
||||
randomDuration := time.Duration(rand.Int63n(int64(window)))
|
||||
rt := start.Add(randomDuration)
|
||||
|
||||
// If the selected time is in the past, attempt renewal immediately.
|
||||
if rt.Before(now) {
|
||||
return &now
|
||||
}
|
||||
|
||||
// Otherwise, if the client can schedule itself to attempt renewal at exactly the selected time, do so.
|
||||
willingToSleepUntil := now.Add(willingToSleep)
|
||||
if willingToSleepUntil.After(rt) || willingToSleepUntil.Equal(rt) {
|
||||
return &rt
|
||||
}
|
||||
|
||||
// TODO: Otherwise, if the selected time is before the next time that the client would wake up normally, attempt renewal immediately.
|
||||
|
||||
// Otherwise, sleep until the next normal wake time, re-check ARI, and return to Step 1.
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRenewalInfo sends a request to the ACME server's renewalInfo endpoint to obtain a suggested renewal window.
|
||||
// The caller MUST provide the certificate and issuer certificate for the certificate they wish to renew.
|
||||
// The caller should attempt to renew the certificate at the time indicated by the ShouldRenewAt method of the returned RenewalInfoResponse object.
|
||||
//
|
||||
// Note: this endpoint is part of a draft specification, not all ACME servers will implement it.
|
||||
// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint.
|
||||
//
|
||||
// https://datatracker.ietf.org/doc/draft-ietf-acme-ari
|
||||
func (c *Certifier) GetRenewalInfo(req RenewalInfoRequest) (*RenewalInfoResponse, error) {
|
||||
certID, err := makeCertID(req.Cert, req.Issuer, req.HashName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error making certID: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.core.Certificates.GetRenewalInfo(certID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var info RenewalInfoResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&info)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// UpdateRenewalInfo sends an update to the ACME server's renewal info endpoint to indicate that the client has successfully replaced a certificate.
|
||||
// A certificate is considered replaced when its revocation would not disrupt any ongoing services,
|
||||
// for instance because it has been renewed and the new certificate is in use, or because it is no longer in use.
|
||||
//
|
||||
// Note: this endpoint is part of a draft specification, not all ACME servers will implement it.
|
||||
// This method will return api.ErrNoARI if the server does not advertise a renewal info endpoint.
|
||||
//
|
||||
// https://datatracker.ietf.org/doc/draft-ietf-acme-ari
|
||||
func (c *Certifier) UpdateRenewalInfo(req RenewalInfoRequest) error {
|
||||
certID, err := makeCertID(req.Cert, req.Issuer, req.HashName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error making certID: %w", err)
|
||||
}
|
||||
|
||||
_, err = c.core.Certificates.UpdateRenewalInfo(acme.RenewalInfoUpdateRequest{
|
||||
CertID: certID,
|
||||
Replaced: true,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// makeCertID returns a base64url-encoded string that uniquely identifies a certificate to endpoints
|
||||
// that implement the draft-ietf-acme-ari specification: https://datatracker.ietf.org/doc/draft-ietf-acme-ari.
|
||||
// hashName must be the string representation of a crypto.Hash constant in the golang.org/x/crypto package.
|
||||
// Supported hash functions are SHA-1, SHA-256, SHA-384, and SHA-512.
|
||||
func makeCertID(leaf, issuer *x509.Certificate, hashName string) (string, error) {
|
||||
if leaf == nil {
|
||||
return "", fmt.Errorf("leaf certificate is nil")
|
||||
}
|
||||
if issuer == nil {
|
||||
return "", fmt.Errorf("issuer certificate is nil")
|
||||
}
|
||||
|
||||
var hashFunc crypto.Hash
|
||||
var oid asn1.ObjectIdentifier
|
||||
|
||||
switch hashName {
|
||||
// The following correlation of hashFunc to OID is copied from a private mapping in golang.org/x/crypto/ocsp:
|
||||
// https://cs.opensource.google/go/x/crypto/+/refs/tags/v0.8.0:ocsp/ocsp.go;l=156
|
||||
case crypto.SHA1.String():
|
||||
hashFunc = crypto.SHA1
|
||||
oid = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26})
|
||||
|
||||
case crypto.SHA256.String():
|
||||
hashFunc = crypto.SHA256
|
||||
oid = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 1})
|
||||
|
||||
case crypto.SHA384.String():
|
||||
hashFunc = crypto.SHA384
|
||||
oid = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 2})
|
||||
|
||||
case crypto.SHA512.String():
|
||||
hashFunc = crypto.SHA512
|
||||
oid = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 3})
|
||||
|
||||
default:
|
||||
return "", fmt.Errorf("hashName %q is not supported by this package", hashName)
|
||||
}
|
||||
|
||||
if !hashFunc.Available() {
|
||||
// This should never happen.
|
||||
return "", fmt.Errorf("hash function %q is not available on your platform", hashFunc)
|
||||
}
|
||||
|
||||
var spki struct {
|
||||
Algorithm pkix.AlgorithmIdentifier
|
||||
PublicKey asn1.BitString
|
||||
}
|
||||
|
||||
_, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &spki)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
h := hashFunc.New()
|
||||
h.Write(spki.PublicKey.RightAlign())
|
||||
issuerKeyHash := h.Sum(nil)
|
||||
|
||||
h.Reset()
|
||||
h.Write(issuer.RawSubject)
|
||||
issuerNameHash := h.Sum(nil)
|
||||
|
||||
type certID struct {
|
||||
HashAlgorithm pkix.AlgorithmIdentifier
|
||||
IssuerNameHash []byte
|
||||
IssuerKeyHash []byte
|
||||
SerialNumber *big.Int
|
||||
}
|
||||
|
||||
// DER-encode the CertID ASN.1 sequence [RFC6960].
|
||||
certIDBytes, err := asn1.Marshal(certID{
|
||||
HashAlgorithm: pkix.AlgorithmIdentifier{
|
||||
Algorithm: oid,
|
||||
},
|
||||
IssuerNameHash: issuerNameHash,
|
||||
IssuerKeyHash: issuerKeyHash,
|
||||
SerialNumber: leaf.SerialNumber,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// base64url-encode [RFC4648] the bytes of the DER-encoded CertID ASN.1 sequence [RFC6960].
|
||||
encodedBytes := base64.URLEncoding.EncodeToString(certIDBytes)
|
||||
|
||||
// Any trailing '=' characters MUST be stripped.
|
||||
return strings.TrimRight(encodedBytes, "="), nil
|
||||
}
|
356
certificate/renewal_test.go
Normal file
356
certificate/renewal_test.go
Normal file
|
@ -0,0 +1,356 @@
|
|||
package certificate
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/go-jose/go-jose/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
ariLeafPEM = `-----BEGIN CERTIFICATE-----
|
||||
MIIDMDCCAhigAwIBAgIIPqNFaGVEHxwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE
|
||||
AxMVbWluaWNhIHJvb3QgY2EgM2ExMzU2MB4XDTIyMDMxNzE3NTEwOVoXDTI0MDQx
|
||||
NjE3NTEwOVowFjEUMBIGA1UEAxMLZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEB
|
||||
AQUAA4IBDwAwggEKAoIBAQCgm9K/c+il2Pf0f8qhgxn9SKqXq88cOm9ov9AVRbPA
|
||||
OWAAewqX2yUAwI4LZBGEgzGzTATkiXfoJ3cN3k39cH6tBbb3iSPuEn7OZpIk9D+e
|
||||
3Q9/hX+N/jlWkaTB/FNA+7aE5IVWhmdczYilXa10V9r+RcvACJt0gsipBZVJ4jfJ
|
||||
HnWJJGRZzzxqG/xkQmpXxZO7nOPFc8SxYKWdfcgp+rjR2ogYhSz7BfKoVakGPbpX
|
||||
vZOuT9z4kkHra/WjwlkQhtHoTXdAxH3qC2UjMzO57Tx+otj0CxAv9O7CTJXISywB
|
||||
vEVcmTSZkHS3eZtvvIwPx7I30ITRkYk/tLl1MbyB3SiZAgMBAAGjeDB2MA4GA1Ud
|
||||
DwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0T
|
||||
AQH/BAIwADAfBgNVHSMEGDAWgBQ4zzDRUaXHVKqlSTWkULGU4zGZpTAWBgNVHREE
|
||||
DzANggtleGFtcGxlLmNvbTANBgkqhkiG9w0BAQsFAAOCAQEAx0aYvmCk7JYGNEXe
|
||||
+hrOfKawkHYzWvA92cI/Oi6h+oSdHZ2UKzwFNf37cVKZ37FCrrv5pFP/xhhHvrNV
|
||||
EnOx4IaF7OrnaTu5miZiUWuvRQP7ZGmGNFYbLTEF6/dj+WqyYdVaWzxRqHFu1ptC
|
||||
TXysJCeyiGnR+KOOjOOQ9ZlO5JUK3OE4hagPLfaIpDDy6RXQt3ss0iNLuB1+IOtp
|
||||
1URpvffLZQ8xPsEgOZyPWOcabTwJrtqBwily+lwPFn2mChUx846LwQfxtsXU/lJg
|
||||
HX2RteNJx7YYNeX3Uf960mgo5an6vE8QNAsIoNHYrGyEmXDhTRe9mCHyiW2S7fZq
|
||||
o9q12g==
|
||||
-----END CERTIFICATE-----`
|
||||
ariIssuerPEM = `-----BEGIN CERTIFICATE-----
|
||||
MIIDSzCCAjOgAwIBAgIIOhNWtJ7Igr0wDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE
|
||||
AxMVbWluaWNhIHJvb3QgY2EgM2ExMzU2MCAXDTIyMDMxNzE3NTEwOVoYDzIxMjIw
|
||||
MzE3MTc1MTA5WjAgMR4wHAYDVQQDExVtaW5pY2Egcm9vdCBjYSAzYTEzNTYwggEi
|
||||
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDc3P6cxcCZ7FQOQrYuigReSa8T
|
||||
IOPNKmlmX9OrTkPwjThiMNEETYKO1ea99yXPK36LUHC6OLmZ9jVQW2Ny1qwQCOy6
|
||||
TrquhnwKgtkBMDAZBLySSEXYdKL3r0jA4sflW130/OLwhstU/yv0J8+pj7eSVOR3
|
||||
zJBnYd1AqnXHRSwQm299KXgqema7uwsa8cgjrXsBzAhrwrvYlVhpWFSv3lQRDFQg
|
||||
c5Z/ZDV9i26qiaJsCCmdisJZWN7N2luUgxdRqzZ4Cr2Xoilg3T+hkb2y/d6ttsPA
|
||||
kaSA+pq3q6Qa7/qfGdT5WuUkcHpvKNRWqnwT9rCYlmG00r3hGgc42D/z1VvfAgMB
|
||||
AAGjgYYwgYMwDgYDVR0PAQH/BAQDAgKEMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggr
|
||||
BgEFBQcDAjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBQ4zzDRUaXHVKql
|
||||
STWkULGU4zGZpTAfBgNVHSMEGDAWgBQ4zzDRUaXHVKqlSTWkULGU4zGZpTANBgkq
|
||||
hkiG9w0BAQsFAAOCAQEArbDHhEjGedjb/YjU80aFTPWOMRjgyfQaPPgyxwX6Dsid
|
||||
1i2H1x4ud4ntz3sTZZxdQIrOqtlIWTWVCjpStwGxaC+38SdreiTTwy/nikXGa/6W
|
||||
ZyQRppR3agh/pl5LHVO6GsJz3YHa7wQhEhj3xsRwa9VrRXgHbLGbPOFVRTHPjaPg
|
||||
Gtsv2PN3f67DsPHF47ASqyOIRpLZPQmZIw6D3isJwfl+8CzvlB1veO0Q3uh08IJc
|
||||
fspYQXvFBzYa64uKxNAJMi4Pby8cf4r36Wnb7cL4ho3fOHgAltxdW8jgibRzqZpQ
|
||||
QKyxn2jX7kxeUDt0hFDJE8lOrhP73m66eBNzxe//FQ==
|
||||
-----END CERTIFICATE-----`
|
||||
ariLeafCertID = "MFswCwYJYIZIAWUDBAIBBCCeWLRusNLb--vmWOkxm34qDjTMWkc3utIhOMoMwKDqbgQg2iiKWySZrD-6c88HMZ6vhIHZPamChLlzGHeZ7pTS8jYCCD6jRWhlRB8c"
|
||||
)
|
||||
|
||||
func Test_makeCertID(t *testing.T) {
|
||||
leaf, err := certcrypto.ParsePEMCertificate([]byte(ariLeafPEM))
|
||||
require.NoError(t, err)
|
||||
issuer, err := certcrypto.ParsePEMCertificate([]byte(ariIssuerPEM))
|
||||
require.NoError(t, err)
|
||||
|
||||
actual, err := makeCertID(leaf, issuer, crypto.SHA256.String())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ariLeafCertID, actual)
|
||||
}
|
||||
|
||||
func TestCertifier_GetRenewalInfo(t *testing.T) {
|
||||
leaf, err := certcrypto.ParsePEMCertificate([]byte(ariLeafPEM))
|
||||
require.NoError(t, err)
|
||||
issuer, err := certcrypto.ParsePEMCertificate([]byte(ariIssuerPEM))
|
||||
require.NoError(t, err)
|
||||
|
||||
// Test with a fake API.
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
mux.HandleFunc("/renewalInfo/"+ariLeafCertID, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, wErr := w.Write([]byte(`{
|
||||
"suggestedWindow": {
|
||||
"start": "2020-03-17T17:51:09Z",
|
||||
"end": "2020-03-17T18:21:09Z"
|
||||
},
|
||||
"explanationUrl": "https://aricapable.ca/docs/renewal-advice/"
|
||||
}
|
||||
}`))
|
||||
require.NoError(t, wErr)
|
||||
})
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
ri, err := certifier.GetRenewalInfo(RenewalInfoRequest{leaf, issuer, crypto.SHA256.String()})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, ri)
|
||||
assert.Equal(t, "2020-03-17T17:51:09Z", ri.SuggestedWindow.Start.Format(time.RFC3339))
|
||||
assert.Equal(t, "2020-03-17T18:21:09Z", ri.SuggestedWindow.End.Format(time.RFC3339))
|
||||
assert.Equal(t, "https://aricapable.ca/docs/renewal-advice/", ri.ExplanationURL)
|
||||
}
|
||||
|
||||
func TestCertifier_GetRenewalInfo_errors(t *testing.T) {
|
||||
leaf, err := certcrypto.ParsePEMCertificate([]byte(ariLeafPEM))
|
||||
require.NoError(t, err)
|
||||
issuer, err := certcrypto.ParsePEMCertificate([]byte(ariIssuerPEM))
|
||||
require.NoError(t, err)
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
httpClient *http.Client
|
||||
request RenewalInfoRequest
|
||||
handler http.HandlerFunc
|
||||
}{
|
||||
{
|
||||
desc: "API timeout",
|
||||
httpClient: &http.Client{Timeout: 500 * time.Millisecond}, // HTTP client that times out after 500ms.
|
||||
request: RenewalInfoRequest{leaf, issuer, crypto.SHA256.String()},
|
||||
handler: func(w http.ResponseWriter, r *http.Request) {
|
||||
// API that takes 2ms to respond.
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "API error",
|
||||
httpClient: http.DefaultClient,
|
||||
request: RenewalInfoRequest{leaf, issuer, crypto.SHA256.String()},
|
||||
handler: func(w http.ResponseWriter, r *http.Request) {
|
||||
// API that responds with error instead of renewal info.
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "Issuer certificate is nil",
|
||||
httpClient: http.DefaultClient,
|
||||
request: RenewalInfoRequest{leaf, nil, crypto.SHA256.String()},
|
||||
handler: func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
mux.HandleFunc("/renewalInfo/"+ariLeafCertID, test.handler)
|
||||
|
||||
core, err := api.New(test.httpClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
response, err := certifier.GetRenewalInfo(test.request)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, response)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertifier_UpdateRenewalInfo(t *testing.T) {
|
||||
leaf, err := certcrypto.ParsePEMCertificate([]byte(ariLeafPEM))
|
||||
require.NoError(t, err)
|
||||
issuer, err := certcrypto.ParsePEMCertificate([]byte(ariIssuerPEM))
|
||||
require.NoError(t, err)
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
// Test with a fake API.
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
mux.HandleFunc("/renewalInfo", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
body, rsbErr := readSignedBody(r, key)
|
||||
if rsbErr != nil {
|
||||
http.Error(w, rsbErr.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req acme.RenewalInfoUpdateRequest
|
||||
err = json.Unmarshal(body, &req)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, req.Replaced)
|
||||
assert.Equal(t, ariLeafCertID, req.CertID)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
err = certifier.UpdateRenewalInfo(RenewalInfoRequest{leaf, issuer, crypto.SHA256.String()})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestCertifier_UpdateRenewalInfo_errors(t *testing.T) {
|
||||
leaf, err := certcrypto.ParsePEMCertificate([]byte(ariLeafPEM))
|
||||
require.NoError(t, err)
|
||||
issuer, err := certcrypto.ParsePEMCertificate([]byte(ariIssuerPEM))
|
||||
require.NoError(t, err)
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
request RenewalInfoRequest
|
||||
}{
|
||||
{
|
||||
desc: "API error",
|
||||
request: RenewalInfoRequest{leaf, issuer, crypto.SHA256.String()},
|
||||
},
|
||||
{
|
||||
desc: "Certificate is nil",
|
||||
request: RenewalInfoRequest{nil, issuer, crypto.SHA256.String()},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
// Always returns an error.
|
||||
mux.HandleFunc("/renewalInfo", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
})
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", key)
|
||||
require.NoError(t, err)
|
||||
|
||||
certifier := NewCertifier(core, &resolverMock{}, CertifierOptions{KeyType: certcrypto.RSA2048})
|
||||
|
||||
err = certifier.UpdateRenewalInfo(test.request)
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewalInfoResponse_ShouldRenew(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
|
||||
t.Run("Window is in the past", func(t *testing.T) {
|
||||
ri := RenewalInfoResponse{
|
||||
acme.RenewalInfoResponse{
|
||||
SuggestedWindow: acme.Window{
|
||||
Start: now.Add(-2 * time.Hour),
|
||||
End: now.Add(-1 * time.Hour),
|
||||
},
|
||||
ExplanationURL: "",
|
||||
},
|
||||
}
|
||||
|
||||
rt := ri.ShouldRenewAt(now, 0)
|
||||
require.NotNil(t, rt)
|
||||
assert.Equal(t, now, *rt)
|
||||
})
|
||||
|
||||
t.Run("Window is in the future", func(t *testing.T) {
|
||||
ri := RenewalInfoResponse{
|
||||
acme.RenewalInfoResponse{
|
||||
SuggestedWindow: acme.Window{
|
||||
Start: now.Add(1 * time.Hour),
|
||||
End: now.Add(2 * time.Hour),
|
||||
},
|
||||
ExplanationURL: "",
|
||||
},
|
||||
}
|
||||
|
||||
rt := ri.ShouldRenewAt(now, 0)
|
||||
assert.Nil(t, rt)
|
||||
})
|
||||
|
||||
t.Run("Window is in the future, but caller is willing to sleep", func(t *testing.T) {
|
||||
ri := RenewalInfoResponse{
|
||||
acme.RenewalInfoResponse{
|
||||
SuggestedWindow: acme.Window{
|
||||
Start: now.Add(1 * time.Hour),
|
||||
End: now.Add(2 * time.Hour),
|
||||
},
|
||||
ExplanationURL: "",
|
||||
},
|
||||
}
|
||||
|
||||
rt := ri.ShouldRenewAt(now, 2*time.Hour)
|
||||
require.NotNil(t, rt)
|
||||
assert.True(t, rt.Before(now.Add(2*time.Hour)))
|
||||
})
|
||||
|
||||
t.Run("Window is in the future, but caller isn't willing to sleep long enough", func(t *testing.T) {
|
||||
ri := RenewalInfoResponse{
|
||||
acme.RenewalInfoResponse{
|
||||
SuggestedWindow: acme.Window{
|
||||
Start: now.Add(1 * time.Hour),
|
||||
End: now.Add(2 * time.Hour),
|
||||
},
|
||||
ExplanationURL: "",
|
||||
},
|
||||
}
|
||||
|
||||
rt := ri.ShouldRenewAt(now, 59*time.Minute)
|
||||
assert.Nil(t, rt)
|
||||
})
|
||||
}
|
||||
|
||||
func readSignedBody(r *http.Request, privateKey *rsa.PrivateKey) ([]byte, error) {
|
||||
reqBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
jws, err := jose.ParseSigned(string(reqBody))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := jws.Verify(&jose.JSONWebKey{
|
||||
Key: privateKey.Public(),
|
||||
Algorithm: "RSA",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
47
challenge/challenges.go
Normal file
47
challenge/challenges.go
Normal file
|
@ -0,0 +1,47 @@
|
|||
package challenge
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
)
|
||||
|
||||
// Type is a string that identifies a particular challenge type and version of ACME challenge.
|
||||
type Type string
|
||||
|
||||
const (
|
||||
// HTTP01 is the "http-01" ACME challenge https://www.rfc-editor.org/rfc/rfc8555.html#section-8.3
|
||||
// Note: ChallengePath returns the URL path to fulfill this challenge.
|
||||
HTTP01 = Type("http-01")
|
||||
|
||||
// DNS01 is the "dns-01" ACME challenge https://www.rfc-editor.org/rfc/rfc8555.html#section-8.4
|
||||
// Note: GetRecord returns a DNS record which will fulfill this challenge.
|
||||
DNS01 = Type("dns-01")
|
||||
|
||||
// TLSALPN01 is the "tls-alpn-01" ACME challenge https://www.rfc-editor.org/rfc/rfc8737.html
|
||||
TLSALPN01 = Type("tls-alpn-01")
|
||||
|
||||
// NNS01 is the "nns-01" ACME challenge
|
||||
NNS01 = Type("nns-01")
|
||||
)
|
||||
|
||||
func (t Type) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func FindChallenge(chlgType Type, authz acme.Authorization) (acme.Challenge, error) {
|
||||
for _, chlg := range authz.Challenges {
|
||||
if chlg.Type == string(chlgType) {
|
||||
return chlg, nil
|
||||
}
|
||||
}
|
||||
|
||||
return acme.Challenge{}, fmt.Errorf("[%s] acme: unable to find challenge %s", GetTargetedDomain(authz), chlgType)
|
||||
}
|
||||
|
||||
func GetTargetedDomain(authz acme.Authorization) string {
|
||||
if authz.Wildcard {
|
||||
return "*." + authz.Identifier.Value
|
||||
}
|
||||
return authz.Identifier.Value
|
||||
}
|
20
challenge/dns01/cname.go
Normal file
20
challenge/dns01/cname.go
Normal file
|
@ -0,0 +1,20 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// Update FQDN with CNAME if any.
|
||||
func updateDomainWithCName(r *dns.Msg, fqdn string) string {
|
||||
for _, rr := range r.Answer {
|
||||
if cn, ok := rr.(*dns.CNAME); ok {
|
||||
if strings.EqualFold(cn.Hdr.Name, fqdn) {
|
||||
return cn.Target
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fqdn
|
||||
}
|
35
challenge/dns01/cname_test.go
Normal file
35
challenge/dns01/cname_test.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_updateDomainWithCName_caseInsensitive(t *testing.T) {
|
||||
qname := "_acme-challenge.uppercase-test.example.com."
|
||||
cnameTarget := "_acme-challenge.uppercase-test.cname-target.example.com."
|
||||
|
||||
msg := &dns.Msg{
|
||||
MsgHdr: dns.MsgHdr{
|
||||
Authoritative: true,
|
||||
},
|
||||
Answer: []dns.RR{
|
||||
&dns.CNAME{
|
||||
Hdr: dns.RR_Header{
|
||||
Name: strings.ToUpper(qname), // CNAME names are case-insensitive
|
||||
Rrtype: dns.TypeCNAME,
|
||||
Class: dns.ClassINET,
|
||||
Ttl: 3600,
|
||||
},
|
||||
Target: cnameTarget,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
fqdn := updateDomainWithCName(msg, qname)
|
||||
|
||||
assert.Equal(t, cnameTarget, fqdn)
|
||||
}
|
238
challenge/dns01/dns_challenge.go
Normal file
238
challenge/dns01/dns_challenge.go
Normal file
|
@ -0,0 +1,238 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/go-acme/lego/v4/platform/wait"
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultPropagationTimeout default propagation timeout.
|
||||
DefaultPropagationTimeout = 60 * time.Second
|
||||
|
||||
// DefaultPollingInterval default polling interval.
|
||||
DefaultPollingInterval = 2 * time.Second
|
||||
|
||||
// DefaultTTL default TTL.
|
||||
DefaultTTL = 120
|
||||
)
|
||||
|
||||
type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error
|
||||
|
||||
type ChallengeOption func(*Challenge) error
|
||||
|
||||
// CondOption Conditional challenge option.
|
||||
func CondOption(condition bool, opt ChallengeOption) ChallengeOption {
|
||||
if !condition {
|
||||
// NoOp options
|
||||
return func(*Challenge) error {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return opt
|
||||
}
|
||||
|
||||
// Challenge implements the dns-01 challenge.
|
||||
type Challenge struct {
|
||||
core *api.Core
|
||||
validate ValidateFunc
|
||||
provider challenge.Provider
|
||||
preCheck preCheck
|
||||
dnsTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider, opts ...ChallengeOption) *Challenge {
|
||||
chlg := &Challenge{
|
||||
core: core,
|
||||
validate: validate,
|
||||
provider: provider,
|
||||
preCheck: newPreCheck(),
|
||||
dnsTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
err := opt(chlg)
|
||||
if err != nil {
|
||||
log.Infof("challenge option error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return chlg
|
||||
}
|
||||
|
||||
// PreSolve just submits the txt record to the dns provider.
|
||||
// It does not validate record propagation, or do anything at all with the acme server.
|
||||
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: %w", domain, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Challenge) Solve(authz acme.Authorization) error {
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
log.Infof("[%s] acme: Trying to solve DNS-01", domain)
|
||||
|
||||
chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Generate the Key Authorization for the challenge
|
||||
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
info := GetChallengeInfo(authz.Identifier.Value, keyAuth)
|
||||
|
||||
var timeout, interval time.Duration
|
||||
switch provider := c.provider.(type) {
|
||||
case challenge.ProviderTimeout:
|
||||
timeout, interval = provider.Timeout()
|
||||
default:
|
||||
timeout, interval = DefaultPropagationTimeout, DefaultPollingInterval
|
||||
}
|
||||
|
||||
log.Infof("[%s] acme: Checking DNS record propagation using %+v", domain, recursiveNameservers)
|
||||
|
||||
time.Sleep(interval)
|
||||
|
||||
err = wait.For("propagation", timeout, interval, func() (bool, error) {
|
||||
stop, errP := c.preCheck.call(domain, info.EffectiveFQDN, info.Value)
|
||||
if !stop || errP != nil {
|
||||
log.Infof("[%s] acme: Waiting for DNS record propagation.", domain)
|
||||
}
|
||||
return stop, errP
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
chlng.KeyAuthorization = keyAuth
|
||||
return c.validate(c.core, domain, chlng)
|
||||
}
|
||||
|
||||
// CleanUp cleans the challenge.
|
||||
func (c *Challenge) CleanUp(authz acme.Authorization) error {
|
||||
log.Infof("[%s] acme: Cleaning DNS-01 challenge", challenge.GetTargetedDomain(authz))
|
||||
|
||||
chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth)
|
||||
}
|
||||
|
||||
func (c *Challenge) Sequential() (bool, time.Duration) {
|
||||
if p, ok := c.provider.(sequential); ok {
|
||||
return ok, p.Sequential()
|
||||
}
|
||||
return false, 0
|
||||
}
|
||||
|
||||
type sequential interface {
|
||||
Sequential() time.Duration
|
||||
}
|
||||
|
||||
// GetRecord returns a DNS record which will fulfill the `dns-01` challenge.
|
||||
// Deprecated: use GetChallengeInfo instead.
|
||||
func GetRecord(domain, keyAuth string) (fqdn, value string) {
|
||||
info := GetChallengeInfo(domain, keyAuth)
|
||||
|
||||
return info.EffectiveFQDN, info.Value
|
||||
}
|
||||
|
||||
// ChallengeInfo contains the information use to create the TXT record.
|
||||
type ChallengeInfo struct {
|
||||
// FQDN is the full-qualified challenge domain (i.e. `_acme-challenge.[domain].`)
|
||||
FQDN string
|
||||
|
||||
// EffectiveFQDN contains the resulting FQDN after the CNAMEs resolutions.
|
||||
EffectiveFQDN string
|
||||
|
||||
// Value contains the value for the TXT record.
|
||||
Value string
|
||||
}
|
||||
|
||||
// GetChallengeInfo returns information used to create a DNS record which will fulfill the `dns-01` challenge.
|
||||
func GetChallengeInfo(domain, keyAuth string) ChallengeInfo {
|
||||
keyAuthShaBytes := sha256.Sum256([]byte(keyAuth))
|
||||
// base64URL encoding without padding
|
||||
value := base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size])
|
||||
|
||||
ok, _ := strconv.ParseBool(os.Getenv("LEGO_DISABLE_CNAME_SUPPORT"))
|
||||
|
||||
return ChallengeInfo{
|
||||
Value: value,
|
||||
FQDN: getChallengeFQDN(domain, false),
|
||||
EffectiveFQDN: getChallengeFQDN(domain, !ok),
|
||||
}
|
||||
}
|
||||
|
||||
func getChallengeFQDN(domain string, followCNAME bool) string {
|
||||
fqdn := fmt.Sprintf("_acme-challenge.%s.", domain)
|
||||
|
||||
if !followCNAME {
|
||||
return fqdn
|
||||
}
|
||||
|
||||
// recursion counter so it doesn't spin out of control
|
||||
for limit := 0; limit < 50; limit++ {
|
||||
// Keep following CNAMEs
|
||||
r, err := dnsQuery(fqdn, dns.TypeCNAME, recursiveNameservers, true)
|
||||
|
||||
if err != nil || r.Rcode != dns.RcodeSuccess {
|
||||
// No more CNAME records to follow, exit
|
||||
break
|
||||
}
|
||||
|
||||
// Check if the domain has CNAME then use that
|
||||
cname := updateDomainWithCName(r, fqdn)
|
||||
if cname == fqdn {
|
||||
break
|
||||
}
|
||||
|
||||
log.Infof("Found CNAME entry for %q: %q", fqdn, cname)
|
||||
|
||||
fqdn = cname
|
||||
}
|
||||
|
||||
return fqdn
|
||||
}
|
59
challenge/dns01/dns_challenge_manual.go
Normal file
59
challenge/dns01/dns_challenge_manual.go
Normal file
|
@ -0,0 +1,59 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
dnsTemplate = `%s %d IN TXT %q`
|
||||
)
|
||||
|
||||
// DNSProviderManual is an implementation of the ChallengeProvider interface.
|
||||
type DNSProviderManual struct{}
|
||||
|
||||
// NewDNSProviderManual returns a DNSProviderManual instance.
|
||||
func NewDNSProviderManual() (*DNSProviderManual, error) {
|
||||
return &DNSProviderManual{}, nil
|
||||
}
|
||||
|
||||
// Present prints instructions for manually creating the TXT record.
|
||||
func (*DNSProviderManual) Present(domain, token, keyAuth string) error {
|
||||
info := GetChallengeInfo(domain, keyAuth)
|
||||
|
||||
authZone, err := FindZoneByFqdn(info.EffectiveFQDN)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("lego: Please create the following TXT record in your %s zone:\n", authZone)
|
||||
fmt.Printf(dnsTemplate+"\n", info.EffectiveFQDN, DefaultTTL, info.Value)
|
||||
fmt.Printf("lego: Press 'Enter' when you are done\n")
|
||||
|
||||
_, err = bufio.NewReader(os.Stdin).ReadBytes('\n')
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// CleanUp prints instructions for manually removing the TXT record.
|
||||
func (*DNSProviderManual) CleanUp(domain, token, keyAuth string) error {
|
||||
info := GetChallengeInfo(domain, keyAuth)
|
||||
|
||||
authZone, err := FindZoneByFqdn(info.EffectiveFQDN)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("lego: You can now remove this TXT record from your %s zone:\n", authZone)
|
||||
fmt.Printf(dnsTemplate+"\n", info.EffectiveFQDN, DefaultTTL, "...")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sequential All DNS challenges for this provider will be resolved sequentially.
|
||||
// Returns the interval between each iteration.
|
||||
func (d *DNSProviderManual) Sequential() time.Duration {
|
||||
return DefaultPropagationTimeout
|
||||
}
|
60
challenge/dns01/dns_challenge_manual_test.go
Normal file
60
challenge/dns01/dns_challenge_manual_test.go
Normal file
|
@ -0,0 +1,60 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDNSProviderManual(t *testing.T) {
|
||||
backupStdin := os.Stdin
|
||||
defer func() { os.Stdin = backupStdin }()
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
input string
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
desc: "Press enter",
|
||||
input: "ok\n",
|
||||
},
|
||||
{
|
||||
desc: "Missing enter",
|
||||
input: "ok",
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
file, err := os.CreateTemp("", "lego_test")
|
||||
assert.NoError(t, err)
|
||||
defer func() { _ = os.Remove(file.Name()) }()
|
||||
|
||||
_, err = file.WriteString(test.input)
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = file.Seek(0, io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
|
||||
os.Stdin = file
|
||||
|
||||
manualProvider, err := NewDNSProviderManual()
|
||||
require.NoError(t, err)
|
||||
|
||||
err = manualProvider.Present("example.com", "", "")
|
||||
if test.expectError {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
|
||||
err = manualProvider.CleanUp("example.com", "", "")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
283
challenge/dns01/dns_challenge_test.go
Normal file
283
challenge/dns01/dns_challenge_test.go
Normal file
|
@ -0,0 +1,283 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"errors"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type providerMock struct {
|
||||
present, cleanUp error
|
||||
}
|
||||
|
||||
func (p *providerMock) Present(domain, token, keyAuth string) error { return p.present }
|
||||
func (p *providerMock) CleanUp(domain, token, keyAuth string) error { return p.cleanUp }
|
||||
|
||||
type providerTimeoutMock struct {
|
||||
present, cleanUp error
|
||||
timeout, interval time.Duration
|
||||
}
|
||||
|
||||
func (p *providerTimeoutMock) Present(domain, token, keyAuth string) error { return p.present }
|
||||
func (p *providerTimeoutMock) CleanUp(domain, token, keyAuth string) error { return p.cleanUp }
|
||||
func (p *providerTimeoutMock) Timeout() (time.Duration, time.Duration) { return p.timeout, p.interval }
|
||||
|
||||
func TestChallenge_PreSolve(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err)
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
validate ValidateFunc
|
||||
preCheck WrapPreCheckFunc
|
||||
provider challenge.Provider
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{},
|
||||
},
|
||||
{
|
||||
desc: "validate fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return errors.New("OOPS") },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
present: nil,
|
||||
cleanUp: nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "preCheck fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return false, errors.New("OOPS") },
|
||||
provider: &providerTimeoutMock{
|
||||
timeout: 2 * time.Second,
|
||||
interval: 500 * time.Millisecond,
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "present fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
present: errors.New("OOPS"),
|
||||
},
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
desc: "cleanUp fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
cleanUp: errors.New("OOPS"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
chlg := NewChallenge(core, test.validate, test.provider, WrapPreCheck(test.preCheck))
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "example.com",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.DNS01.String()},
|
||||
},
|
||||
}
|
||||
|
||||
err = chlg.PreSolve(authz)
|
||||
if test.expectError {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallenge_Solve(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err)
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
validate ValidateFunc
|
||||
preCheck WrapPreCheckFunc
|
||||
provider challenge.Provider
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{},
|
||||
},
|
||||
{
|
||||
desc: "validate fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return errors.New("OOPS") },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
present: nil,
|
||||
cleanUp: nil,
|
||||
},
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
desc: "preCheck fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return false, errors.New("OOPS") },
|
||||
provider: &providerTimeoutMock{
|
||||
timeout: 2 * time.Second,
|
||||
interval: 500 * time.Millisecond,
|
||||
},
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
desc: "present fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
present: errors.New("OOPS"),
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "cleanUp fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
cleanUp: errors.New("OOPS"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
var options []ChallengeOption
|
||||
if test.preCheck != nil {
|
||||
options = append(options, WrapPreCheck(test.preCheck))
|
||||
}
|
||||
chlg := NewChallenge(core, test.validate, test.provider, options...)
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "example.com",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.DNS01.String()},
|
||||
},
|
||||
}
|
||||
|
||||
err = chlg.Solve(authz)
|
||||
if test.expectError {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallenge_CleanUp(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err)
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
validate ValidateFunc
|
||||
preCheck WrapPreCheckFunc
|
||||
provider challenge.Provider
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{},
|
||||
},
|
||||
{
|
||||
desc: "validate fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return errors.New("OOPS") },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
present: nil,
|
||||
cleanUp: nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "preCheck fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return false, errors.New("OOPS") },
|
||||
provider: &providerTimeoutMock{
|
||||
timeout: 2 * time.Second,
|
||||
interval: 500 * time.Millisecond,
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "present fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
present: errors.New("OOPS"),
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "cleanUp fail",
|
||||
validate: func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
preCheck: func(_, _, _ string, _ PreCheckFunc) (bool, error) { return true, nil },
|
||||
provider: &providerMock{
|
||||
cleanUp: errors.New("OOPS"),
|
||||
},
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
chlg := NewChallenge(core, test.validate, test.provider, WrapPreCheck(test.preCheck))
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "example.com",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.DNS01.String()},
|
||||
},
|
||||
}
|
||||
|
||||
err = chlg.CleanUp(authz)
|
||||
if test.expectError {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
24
challenge/dns01/domain.go
Normal file
24
challenge/dns01/domain.go
Normal file
|
@ -0,0 +1,24 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// ExtractSubDomain extracts the subdomain part from a domain and a zone.
|
||||
func ExtractSubDomain(domain, zone string) (string, error) {
|
||||
canonDomain := dns.Fqdn(domain)
|
||||
canonZone := dns.Fqdn(zone)
|
||||
|
||||
if canonDomain == canonZone {
|
||||
return "", fmt.Errorf("no subdomain because the domain and the zone are identical: %s", canonDomain)
|
||||
}
|
||||
|
||||
if !dns.IsSubDomain(canonZone, canonDomain) {
|
||||
return "", fmt.Errorf("%s is not a subdomain of %s", canonDomain, canonZone)
|
||||
}
|
||||
|
||||
return strings.TrimSuffix(canonDomain, "."+canonZone), nil
|
||||
}
|
104
challenge/dns01/domain_test.go
Normal file
104
challenge/dns01/domain_test.go
Normal file
|
@ -0,0 +1,104 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestExtractSubDomain(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
domain string
|
||||
zone string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "no FQDN",
|
||||
domain: "_acme-challenge.example.com",
|
||||
zone: "example.com",
|
||||
expected: "_acme-challenge",
|
||||
},
|
||||
{
|
||||
desc: "no FQDN zone",
|
||||
domain: "_acme-challenge.example.com.",
|
||||
zone: "example.com",
|
||||
expected: "_acme-challenge",
|
||||
},
|
||||
{
|
||||
desc: "no FQDN domain",
|
||||
domain: "_acme-challenge.example.com",
|
||||
zone: "example.com.",
|
||||
expected: "_acme-challenge",
|
||||
},
|
||||
{
|
||||
desc: "FQDN",
|
||||
domain: "_acme-challenge.example.com.",
|
||||
zone: "example.com.",
|
||||
expected: "_acme-challenge",
|
||||
},
|
||||
{
|
||||
desc: "multi-level subdomain",
|
||||
domain: "_acme-challenge.one.example.com.",
|
||||
zone: "example.com.",
|
||||
expected: "_acme-challenge.one",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
subDomain, err := ExtractSubDomain(test.domain, test.zone)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, test.expected, subDomain)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractSubDomain_errors(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
domain string
|
||||
zone string
|
||||
}{
|
||||
{
|
||||
desc: "same domain",
|
||||
domain: "example.com",
|
||||
zone: "example.com",
|
||||
},
|
||||
{
|
||||
desc: "same domain, no FQDN zone",
|
||||
domain: "example.com.",
|
||||
zone: "example.com",
|
||||
},
|
||||
{
|
||||
desc: "same domain, no FQDN domain",
|
||||
domain: "example.com",
|
||||
zone: "example.com.",
|
||||
},
|
||||
{
|
||||
desc: "same domain, FQDN",
|
||||
domain: "example.com.",
|
||||
zone: "example.com.",
|
||||
},
|
||||
{
|
||||
desc: "zone and domain are unrelated",
|
||||
domain: "_acme-challenge.example.com",
|
||||
zone: "example.org",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := ExtractSubDomain(test.domain, test.zone)
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
5
challenge/dns01/fixtures/resolv.conf.1
Normal file
5
challenge/dns01/fixtures/resolv.conf.1
Normal file
|
@ -0,0 +1,5 @@
|
|||
domain company.com
|
||||
nameserver 10.200.3.249
|
||||
nameserver 10.200.3.250:5353
|
||||
nameserver 2001:4860:4860::8844
|
||||
nameserver [10.0.0.1]:5353
|
19
challenge/dns01/fqdn.go
Normal file
19
challenge/dns01/fqdn.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
package dns01
|
||||
|
||||
// ToFqdn converts the name into a fqdn appending a trailing dot.
|
||||
func ToFqdn(name string) string {
|
||||
n := len(name)
|
||||
if n == 0 || name[n-1] == '.' {
|
||||
return name
|
||||
}
|
||||
return name + "."
|
||||
}
|
||||
|
||||
// UnFqdn converts the fqdn into a name removing the trailing dot.
|
||||
func UnFqdn(name string) string {
|
||||
n := len(name)
|
||||
if n != 0 && name[n-1] == '.' {
|
||||
return name[:n-1]
|
||||
}
|
||||
return name
|
||||
}
|
66
challenge/dns01/fqdn_test.go
Normal file
66
challenge/dns01/fqdn_test.go
Normal file
|
@ -0,0 +1,66 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestToFqdn(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
domain string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "simple",
|
||||
domain: "foo.bar.com",
|
||||
expected: "foo.bar.com.",
|
||||
},
|
||||
{
|
||||
desc: "already FQDN",
|
||||
domain: "foo.bar.com.",
|
||||
expected: "foo.bar.com.",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fqdn := ToFqdn(test.domain)
|
||||
assert.Equal(t, test.expected, fqdn)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnFqdn(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
fqdn string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "simple",
|
||||
fqdn: "foo.bar.com.",
|
||||
expected: "foo.bar.com",
|
||||
},
|
||||
{
|
||||
desc: "already domain",
|
||||
fqdn: "foo.bar.com",
|
||||
expected: "foo.bar.com",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
domain := UnFqdn(test.fqdn)
|
||||
|
||||
assert.Equal(t, test.expected, domain)
|
||||
})
|
||||
}
|
||||
}
|
290
challenge/dns01/nameserver.go
Normal file
290
challenge/dns01/nameserver.go
Normal file
|
@ -0,0 +1,290 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
const defaultResolvConf = "/etc/resolv.conf"
|
||||
|
||||
var (
|
||||
fqdnSoaCache = map[string]*soaCacheEntry{}
|
||||
muFqdnSoaCache sync.Mutex
|
||||
)
|
||||
|
||||
var defaultNameservers = []string{
|
||||
"google-public-dns-a.google.com:53",
|
||||
"google-public-dns-b.google.com:53",
|
||||
}
|
||||
|
||||
// recursiveNameservers are used to pre-check DNS propagation.
|
||||
var recursiveNameservers = getNameservers(defaultResolvConf, defaultNameservers)
|
||||
|
||||
// soaCacheEntry holds a cached SOA record (only selected fields).
|
||||
type soaCacheEntry struct {
|
||||
zone string // zone apex (a domain name)
|
||||
primaryNs string // primary nameserver for the zone apex
|
||||
expires time.Time // time when this cache entry should be evicted
|
||||
}
|
||||
|
||||
func newSoaCacheEntry(soa *dns.SOA) *soaCacheEntry {
|
||||
return &soaCacheEntry{
|
||||
zone: soa.Hdr.Name,
|
||||
primaryNs: soa.Ns,
|
||||
expires: time.Now().Add(time.Duration(soa.Refresh) * time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
// isExpired checks whether a cache entry should be considered expired.
|
||||
func (cache *soaCacheEntry) isExpired() bool {
|
||||
return time.Now().After(cache.expires)
|
||||
}
|
||||
|
||||
// ClearFqdnCache clears the cache of fqdn to zone mappings. Primarily used in testing.
|
||||
func ClearFqdnCache() {
|
||||
muFqdnSoaCache.Lock()
|
||||
fqdnSoaCache = map[string]*soaCacheEntry{}
|
||||
muFqdnSoaCache.Unlock()
|
||||
}
|
||||
|
||||
func AddDNSTimeout(timeout time.Duration) ChallengeOption {
|
||||
return func(_ *Challenge) error {
|
||||
dnsTimeout = timeout
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func AddRecursiveNameservers(nameservers []string) ChallengeOption {
|
||||
return func(_ *Challenge) error {
|
||||
recursiveNameservers = ParseNameservers(nameservers)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// getNameservers attempts to get systems nameservers before falling back to the defaults.
|
||||
func getNameservers(path string, defaults []string) []string {
|
||||
config, err := dns.ClientConfigFromFile(path)
|
||||
if err != nil || len(config.Servers) == 0 {
|
||||
return defaults
|
||||
}
|
||||
|
||||
return ParseNameservers(config.Servers)
|
||||
}
|
||||
|
||||
func ParseNameservers(servers []string) []string {
|
||||
var resolvers []string
|
||||
for _, resolver := range servers {
|
||||
// ensure all servers have a port number
|
||||
if _, _, err := net.SplitHostPort(resolver); err != nil {
|
||||
resolvers = append(resolvers, net.JoinHostPort(resolver, "53"))
|
||||
} else {
|
||||
resolvers = append(resolvers, resolver)
|
||||
}
|
||||
}
|
||||
return resolvers
|
||||
}
|
||||
|
||||
// lookupNameservers returns the authoritative nameservers for the given fqdn.
|
||||
func lookupNameservers(fqdn string) ([]string, error) {
|
||||
var authoritativeNss []string
|
||||
|
||||
zone, err := FindZoneByFqdn(fqdn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not determine the zone: %w", err)
|
||||
}
|
||||
|
||||
r, err := dnsQuery(zone, dns.TypeNS, recursiveNameservers, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, rr := range r.Answer {
|
||||
if ns, ok := rr.(*dns.NS); ok {
|
||||
authoritativeNss = append(authoritativeNss, strings.ToLower(ns.Ns))
|
||||
}
|
||||
}
|
||||
|
||||
if len(authoritativeNss) > 0 {
|
||||
return authoritativeNss, nil
|
||||
}
|
||||
return nil, errors.New("could not determine authoritative nameservers")
|
||||
}
|
||||
|
||||
// FindPrimaryNsByFqdn determines the primary nameserver of the zone apex for the given fqdn
|
||||
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
|
||||
func FindPrimaryNsByFqdn(fqdn string) (string, error) {
|
||||
return FindPrimaryNsByFqdnCustom(fqdn, recursiveNameservers)
|
||||
}
|
||||
|
||||
// FindPrimaryNsByFqdnCustom determines the primary nameserver of the zone apex for the given fqdn
|
||||
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
|
||||
func FindPrimaryNsByFqdnCustom(fqdn string, nameservers []string) (string, error) {
|
||||
soa, err := lookupSoaByFqdn(fqdn, nameservers)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return soa.primaryNs, nil
|
||||
}
|
||||
|
||||
// FindZoneByFqdn determines the zone apex for the given fqdn
|
||||
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
|
||||
func FindZoneByFqdn(fqdn string) (string, error) {
|
||||
return FindZoneByFqdnCustom(fqdn, recursiveNameservers)
|
||||
}
|
||||
|
||||
// FindZoneByFqdnCustom determines the zone apex for the given fqdn
|
||||
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
|
||||
func FindZoneByFqdnCustom(fqdn string, nameservers []string) (string, error) {
|
||||
soa, err := lookupSoaByFqdn(fqdn, nameservers)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return soa.zone, nil
|
||||
}
|
||||
|
||||
func lookupSoaByFqdn(fqdn string, nameservers []string) (*soaCacheEntry, error) {
|
||||
muFqdnSoaCache.Lock()
|
||||
defer muFqdnSoaCache.Unlock()
|
||||
|
||||
// Do we have it cached and is it still fresh?
|
||||
if ent := fqdnSoaCache[fqdn]; ent != nil && !ent.isExpired() {
|
||||
return ent, nil
|
||||
}
|
||||
|
||||
ent, err := fetchSoaByFqdn(fqdn, nameservers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fqdnSoaCache[fqdn] = ent
|
||||
return ent, nil
|
||||
}
|
||||
|
||||
func fetchSoaByFqdn(fqdn string, nameservers []string) (*soaCacheEntry, error) {
|
||||
var err error
|
||||
var in *dns.Msg
|
||||
|
||||
labelIndexes := dns.Split(fqdn)
|
||||
for _, index := range labelIndexes {
|
||||
domain := fqdn[index:]
|
||||
|
||||
in, err = dnsQuery(domain, dns.TypeSOA, nameservers, true)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if in == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch in.Rcode {
|
||||
case dns.RcodeSuccess:
|
||||
// Check if we got a SOA RR in the answer section
|
||||
if len(in.Answer) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// CNAME records cannot/should not exist at the root of a zone.
|
||||
// So we skip a domain when a CNAME is found.
|
||||
if dnsMsgContainsCNAME(in) {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, ans := range in.Answer {
|
||||
if soa, ok := ans.(*dns.SOA); ok {
|
||||
return newSoaCacheEntry(soa), nil
|
||||
}
|
||||
}
|
||||
case dns.RcodeNameError:
|
||||
// NXDOMAIN
|
||||
default:
|
||||
// Any response code other than NOERROR and NXDOMAIN is treated as error
|
||||
return nil, fmt.Errorf("unexpected response code '%s' for %s", dns.RcodeToString[in.Rcode], domain)
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("could not find the start of authority for %s%s", fqdn, formatDNSError(in, err))
|
||||
}
|
||||
|
||||
// dnsMsgContainsCNAME checks for a CNAME answer in msg.
|
||||
func dnsMsgContainsCNAME(msg *dns.Msg) bool {
|
||||
for _, ans := range msg.Answer {
|
||||
if _, ok := ans.(*dns.CNAME); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func dnsQuery(fqdn string, rtype uint16, nameservers []string, recursive bool) (*dns.Msg, error) {
|
||||
m := createDNSMsg(fqdn, rtype, recursive)
|
||||
|
||||
var in *dns.Msg
|
||||
var err error
|
||||
|
||||
for _, ns := range nameservers {
|
||||
in, err = sendDNSQuery(m, ns)
|
||||
if err == nil && len(in.Answer) > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return in, err
|
||||
}
|
||||
|
||||
func createDNSMsg(fqdn string, rtype uint16, recursive bool) *dns.Msg {
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion(fqdn, rtype)
|
||||
m.SetEdns0(4096, false)
|
||||
|
||||
if !recursive {
|
||||
m.RecursionDesired = false
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func sendDNSQuery(m *dns.Msg, ns string) (*dns.Msg, error) {
|
||||
if ok, _ := strconv.ParseBool(os.Getenv("LEGO_EXPERIMENTAL_DNS_TCP_ONLY")); ok {
|
||||
tcp := &dns.Client{Net: "tcp", Timeout: dnsTimeout}
|
||||
in, _, err := tcp.Exchange(m, ns)
|
||||
|
||||
return in, err
|
||||
}
|
||||
|
||||
udp := &dns.Client{Net: "udp", Timeout: dnsTimeout}
|
||||
in, _, err := udp.Exchange(m, ns)
|
||||
|
||||
if in != nil && in.Truncated {
|
||||
tcp := &dns.Client{Net: "tcp", Timeout: dnsTimeout}
|
||||
// If the TCP request succeeds, the err will reset to nil
|
||||
in, _, err = tcp.Exchange(m, ns)
|
||||
}
|
||||
|
||||
return in, err
|
||||
}
|
||||
|
||||
func formatDNSError(msg *dns.Msg, err error) string {
|
||||
var parts []string
|
||||
|
||||
if msg != nil {
|
||||
parts = append(parts, dns.RcodeToString[msg.Rcode])
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
parts = append(parts, err.Error())
|
||||
}
|
||||
|
||||
if len(parts) > 0 {
|
||||
return ": " + strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
199
challenge/dns01/nameserver_test.go
Normal file
199
challenge/dns01/nameserver_test.go
Normal file
|
@ -0,0 +1,199 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLookupNameserversOK(t *testing.T) {
|
||||
testCases := []struct {
|
||||
fqdn string
|
||||
nss []string
|
||||
}{
|
||||
{
|
||||
fqdn: "en.wikipedia.org.",
|
||||
nss: []string{"ns0.wikimedia.org.", "ns1.wikimedia.org.", "ns2.wikimedia.org."},
|
||||
},
|
||||
{
|
||||
fqdn: "www.google.com.",
|
||||
nss: []string{"ns1.google.com.", "ns2.google.com.", "ns3.google.com.", "ns4.google.com."},
|
||||
},
|
||||
{
|
||||
fqdn: "physics.georgetown.edu.",
|
||||
nss: []string{"ns4.georgetown.edu.", "ns5.georgetown.edu.", "ns6.georgetown.edu."},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.fqdn, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
nss, err := lookupNameservers(test.fqdn)
|
||||
require.NoError(t, err)
|
||||
|
||||
sort.Strings(nss)
|
||||
sort.Strings(test.nss)
|
||||
|
||||
assert.EqualValues(t, test.nss, nss)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupNameserversErr(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
fqdn string
|
||||
error string
|
||||
}{
|
||||
{
|
||||
desc: "invalid tld",
|
||||
fqdn: "_null.n0n0.",
|
||||
error: "could not determine the zone",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := lookupNameservers(test.fqdn)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), test.error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var findXByFqdnTestCases = []struct {
|
||||
desc string
|
||||
fqdn string
|
||||
zone string
|
||||
primaryNs string
|
||||
nameservers []string
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
desc: "domain is a CNAME",
|
||||
fqdn: "mail.google.com.",
|
||||
zone: "google.com.",
|
||||
primaryNs: "ns1.google.com.",
|
||||
nameservers: recursiveNameservers,
|
||||
},
|
||||
{
|
||||
desc: "domain is a non-existent subdomain",
|
||||
fqdn: "foo.google.com.",
|
||||
zone: "google.com.",
|
||||
primaryNs: "ns1.google.com.",
|
||||
nameservers: recursiveNameservers,
|
||||
},
|
||||
{
|
||||
desc: "domain is a eTLD",
|
||||
fqdn: "example.com.ac.",
|
||||
zone: "ac.",
|
||||
primaryNs: "a0.nic.ac.",
|
||||
nameservers: recursiveNameservers,
|
||||
},
|
||||
{
|
||||
desc: "domain is a cross-zone CNAME",
|
||||
fqdn: "cross-zone-example.assets.sh.",
|
||||
zone: "assets.sh.",
|
||||
primaryNs: "gina.ns.cloudflare.com.",
|
||||
nameservers: recursiveNameservers,
|
||||
},
|
||||
{
|
||||
desc: "NXDOMAIN",
|
||||
fqdn: "test.lego.zz.",
|
||||
zone: "lego.zz.",
|
||||
nameservers: []string{"8.8.8.8:53"},
|
||||
expectedError: "could not find the start of authority for test.lego.zz.: NXDOMAIN",
|
||||
},
|
||||
{
|
||||
desc: "several non existent nameservers",
|
||||
fqdn: "mail.google.com.",
|
||||
zone: "google.com.",
|
||||
primaryNs: "ns1.google.com.",
|
||||
nameservers: []string{":7053", ":8053", "8.8.8.8:53"},
|
||||
},
|
||||
{
|
||||
desc: "only non-existent nameservers",
|
||||
fqdn: "mail.google.com.",
|
||||
zone: "google.com.",
|
||||
nameservers: []string{":7053", ":8053", ":9053"},
|
||||
expectedError: "could not find the start of authority for mail.google.com.: read udp",
|
||||
},
|
||||
{
|
||||
desc: "no nameservers",
|
||||
fqdn: "test.ldez.com.",
|
||||
zone: "ldez.com.",
|
||||
nameservers: []string{},
|
||||
expectedError: "could not find the start of authority for test.ldez.com.",
|
||||
},
|
||||
}
|
||||
|
||||
func TestFindZoneByFqdnCustom(t *testing.T) {
|
||||
for _, test := range findXByFqdnTestCases {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
ClearFqdnCache()
|
||||
|
||||
zone, err := FindZoneByFqdnCustom(test.fqdn, test.nameservers)
|
||||
if test.expectedError != "" {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), test.expectedError)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.zone, zone)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindPrimaryNsByFqdnCustom(t *testing.T) {
|
||||
for _, test := range findXByFqdnTestCases {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
ClearFqdnCache()
|
||||
|
||||
ns, err := FindPrimaryNsByFqdnCustom(test.fqdn, test.nameservers)
|
||||
if test.expectedError != "" {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), test.expectedError)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.primaryNs, ns)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveConfServers(t *testing.T) {
|
||||
testCases := []struct {
|
||||
fixture string
|
||||
expected []string
|
||||
defaults []string
|
||||
}{
|
||||
{
|
||||
fixture: "fixtures/resolv.conf.1",
|
||||
defaults: []string{"127.0.0.1:53"},
|
||||
expected: []string{"10.200.3.249:53", "10.200.3.250:5353", "[2001:4860:4860::8844]:53", "[10.0.0.1]:5353"},
|
||||
},
|
||||
{
|
||||
fixture: "fixtures/resolv.conf.nonexistant",
|
||||
defaults: []string{"127.0.0.1:53"},
|
||||
expected: []string{"127.0.0.1:53"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.fixture, func(t *testing.T) {
|
||||
result := getNameservers(test.fixture, test.defaults)
|
||||
|
||||
sort.Strings(result)
|
||||
sort.Strings(test.expected)
|
||||
|
||||
assert.Equal(t, test.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
8
challenge/dns01/nameserver_unix.go
Normal file
8
challenge/dns01/nameserver_unix.go
Normal file
|
@ -0,0 +1,8 @@
|
|||
//go:build !windows
|
||||
|
||||
package dns01
|
||||
|
||||
import "time"
|
||||
|
||||
// dnsTimeout is used to override the default DNS timeout of 10 seconds.
|
||||
var dnsTimeout = 10 * time.Second
|
8
challenge/dns01/nameserver_windows.go
Normal file
8
challenge/dns01/nameserver_windows.go
Normal file
|
@ -0,0 +1,8 @@
|
|||
//go:build windows
|
||||
|
||||
package dns01
|
||||
|
||||
import "time"
|
||||
|
||||
// dnsTimeout is used to override the default DNS timeout of 20 seconds.
|
||||
var dnsTimeout = 20 * time.Second
|
110
challenge/dns01/precheck.go
Normal file
110
challenge/dns01/precheck.go
Normal file
|
@ -0,0 +1,110 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// PreCheckFunc checks DNS propagation before notifying ACME that the DNS challenge is ready.
|
||||
type PreCheckFunc func(fqdn, value string) (bool, error)
|
||||
|
||||
// WrapPreCheckFunc wraps a PreCheckFunc in order to do extra operations before or after
|
||||
// the main check, put it in a loop, etc.
|
||||
type WrapPreCheckFunc func(domain, fqdn, value string, check PreCheckFunc) (bool, error)
|
||||
|
||||
// WrapPreCheck Allow to define checks before notifying ACME that the DNS challenge is ready.
|
||||
func WrapPreCheck(wrap WrapPreCheckFunc) ChallengeOption {
|
||||
return func(chlg *Challenge) error {
|
||||
chlg.preCheck.checkFunc = wrap
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func DisableCompletePropagationRequirement() ChallengeOption {
|
||||
return func(chlg *Challenge) error {
|
||||
chlg.preCheck.requireCompletePropagation = false
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type preCheck struct {
|
||||
// checks DNS propagation before notifying ACME that the DNS challenge is ready.
|
||||
checkFunc WrapPreCheckFunc
|
||||
// require the TXT record to be propagated to all authoritative name servers
|
||||
requireCompletePropagation bool
|
||||
}
|
||||
|
||||
func newPreCheck() preCheck {
|
||||
return preCheck{
|
||||
requireCompletePropagation: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (p preCheck) call(domain, fqdn, value string) (bool, error) {
|
||||
if p.checkFunc == nil {
|
||||
return p.checkDNSPropagation(fqdn, value)
|
||||
}
|
||||
|
||||
return p.checkFunc(domain, fqdn, value, p.checkDNSPropagation)
|
||||
}
|
||||
|
||||
// checkDNSPropagation checks if the expected TXT record has been propagated to all authoritative nameservers.
|
||||
func (p preCheck) checkDNSPropagation(fqdn, value string) (bool, error) {
|
||||
// Initial attempt to resolve at the recursive NS
|
||||
r, err := dnsQuery(fqdn, dns.TypeTXT, recursiveNameservers, true)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if !p.requireCompletePropagation {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
if r.Rcode == dns.RcodeSuccess {
|
||||
fqdn = updateDomainWithCName(r, fqdn)
|
||||
}
|
||||
|
||||
authoritativeNss, err := lookupNameservers(fqdn)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return checkAuthoritativeNss(fqdn, value, authoritativeNss)
|
||||
}
|
||||
|
||||
// checkAuthoritativeNss queries each of the given nameservers for the expected TXT record.
|
||||
func checkAuthoritativeNss(fqdn, value string, nameservers []string) (bool, error) {
|
||||
for _, ns := range nameservers {
|
||||
r, err := dnsQuery(fqdn, dns.TypeTXT, []string{net.JoinHostPort(ns, "53")}, false)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if r.Rcode != dns.RcodeSuccess {
|
||||
return false, fmt.Errorf("NS %s returned %s for %s", ns, dns.RcodeToString[r.Rcode], fqdn)
|
||||
}
|
||||
|
||||
var records []string
|
||||
|
||||
var found bool
|
||||
for _, rr := range r.Answer {
|
||||
if txt, ok := rr.(*dns.TXT); ok {
|
||||
record := strings.Join(txt.Txt, "")
|
||||
records = append(records, record)
|
||||
if record == value {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
return false, fmt.Errorf("NS %s did not return the expected TXT record [fqdn: %s, value: %s]: %s", ns, fqdn, value, strings.Join(records, " ,"))
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
117
challenge/dns01/precheck_test.go
Normal file
117
challenge/dns01/precheck_test.go
Normal file
|
@ -0,0 +1,117 @@
|
|||
package dns01
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCheckDNSPropagation(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
fqdn string
|
||||
value string
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
fqdn: "postman-echo.com.",
|
||||
value: "postman-domain-verification=c85de626cb79d941310696e06558e2e790223802f3697dfbdcaf65510152d52c",
|
||||
},
|
||||
{
|
||||
desc: "no TXT record",
|
||||
fqdn: "acme-staging.api.letsencrypt.org.",
|
||||
value: "fe01=",
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ClearFqdnCache()
|
||||
|
||||
check := newPreCheck()
|
||||
|
||||
ok, err := check.checkDNSPropagation(test.fqdn, test.value)
|
||||
if test.expectError {
|
||||
assert.Errorf(t, err, "PreCheckDNS must failed for %s", test.fqdn)
|
||||
assert.False(t, ok, "PreCheckDNS must failed for %s", test.fqdn)
|
||||
} else {
|
||||
assert.NoErrorf(t, err, "PreCheckDNS failed for %s", test.fqdn)
|
||||
assert.True(t, ok, "PreCheckDNS failed for %s", test.fqdn)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckAuthoritativeNss(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
fqdn, value string
|
||||
ns []string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
desc: "TXT RR w/ expected value",
|
||||
fqdn: "8.8.8.8.asn.routeviews.org.",
|
||||
value: "151698.8.8.024",
|
||||
ns: []string{"asnums.routeviews.org."},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
desc: "No TXT RR",
|
||||
fqdn: "ns1.google.com.",
|
||||
ns: []string{"ns2.google.com."},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ClearFqdnCache()
|
||||
|
||||
ok, _ := checkAuthoritativeNss(test.fqdn, test.value, test.ns)
|
||||
assert.Equal(t, test.expected, ok, test.fqdn)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckAuthoritativeNssErr(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
fqdn, value string
|
||||
ns []string
|
||||
error string
|
||||
}{
|
||||
{
|
||||
desc: "TXT RR /w unexpected value",
|
||||
fqdn: "8.8.8.8.asn.routeviews.org.",
|
||||
value: "fe01=",
|
||||
ns: []string{"asnums.routeviews.org."},
|
||||
error: "did not return the expected TXT record",
|
||||
},
|
||||
{
|
||||
desc: "No TXT RR",
|
||||
fqdn: "ns1.google.com.",
|
||||
value: "fe01=",
|
||||
ns: []string{"ns2.google.com."},
|
||||
error: "did not return the expected TXT record",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ClearFqdnCache()
|
||||
|
||||
_, err := checkAuthoritativeNss(test.fqdn, test.value, test.ns)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), test.error)
|
||||
})
|
||||
}
|
||||
}
|
187
challenge/http01/domain_matcher.go
Normal file
187
challenge/http01/domain_matcher.go
Normal file
|
@ -0,0 +1,187 @@
|
|||
package http01
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A domainMatcher tries to match a domain (the one we're requesting a certificate for)
|
||||
// in the HTTP request coming from the ACME validation servers.
|
||||
// This step is part of DNS rebind attack prevention,
|
||||
// where the webserver matches incoming requests to a list of domain the server acts authoritative for.
|
||||
//
|
||||
// The most simple check involves finding the domain in the HTTP Host header;
|
||||
// this is what hostMatcher does.
|
||||
// Use it, when the http01.ProviderServer is directly reachable from the internet,
|
||||
// or when it operates behind a transparent proxy.
|
||||
//
|
||||
// In many (reverse) proxy setups, Apache and NGINX traditionally move the Host header to a new header named X-Forwarded-Host.
|
||||
// Use arbitraryMatcher("X-Forwarded-Host") in this case,
|
||||
// or the appropriate header name for other proxy servers.
|
||||
//
|
||||
// RFC7239 has standardized the different forwarding headers into a single header named Forwarded.
|
||||
// The header value has a different format, so you should use forwardedMatcher
|
||||
// when the http01.ProviderServer operates behind a RFC7239 compatible proxy.
|
||||
// https://www.rfc-editor.org/rfc/rfc7239.html
|
||||
//
|
||||
// Note: RFC7239 also reminds us, "that an HTTP list [...] may be split over multiple header fields" (section 7.1),
|
||||
// meaning that
|
||||
//
|
||||
// X-Header: a
|
||||
// X-Header: b
|
||||
//
|
||||
// is equal to
|
||||
//
|
||||
// X-Header: a, b
|
||||
//
|
||||
// All matcher implementations (explicitly not excluding arbitraryMatcher!)
|
||||
// have in common that they only match against the first value in such lists.
|
||||
type domainMatcher interface {
|
||||
// matches checks whether the request is valid for the given domain.
|
||||
matches(request *http.Request, domain string) bool
|
||||
|
||||
// name returns the header name used in the check.
|
||||
// This is primarily used to create meaningful error messages.
|
||||
name() string
|
||||
}
|
||||
|
||||
// hostMatcher checks whether (*net/http).Request.Host starts with a domain name.
|
||||
type hostMatcher struct{}
|
||||
|
||||
func (m *hostMatcher) name() string {
|
||||
return "Host"
|
||||
}
|
||||
|
||||
func (m *hostMatcher) matches(r *http.Request, domain string) bool {
|
||||
return strings.HasPrefix(r.Host, domain)
|
||||
}
|
||||
|
||||
// hostMatcher checks whether the specified (*net/http.Request).Header value starts with a domain name.
|
||||
type arbitraryMatcher string
|
||||
|
||||
func (m arbitraryMatcher) name() string {
|
||||
return string(m)
|
||||
}
|
||||
|
||||
func (m arbitraryMatcher) matches(r *http.Request, domain string) bool {
|
||||
return strings.HasPrefix(r.Header.Get(m.name()), domain)
|
||||
}
|
||||
|
||||
// forwardedMatcher checks whether the Forwarded header contains a "host" element starting with a domain name.
|
||||
// See https://www.rfc-editor.org/rfc/rfc7239.html for details.
|
||||
type forwardedMatcher struct{}
|
||||
|
||||
func (m *forwardedMatcher) name() string {
|
||||
return "Forwarded"
|
||||
}
|
||||
|
||||
func (m *forwardedMatcher) matches(r *http.Request, domain string) bool {
|
||||
fwds, err := parseForwardedHeader(r.Header.Get(m.name()))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(fwds) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
host := fwds[0]["host"]
|
||||
return strings.HasPrefix(host, domain)
|
||||
}
|
||||
|
||||
// parsing requires some form of state machine.
|
||||
func parseForwardedHeader(s string) (elements []map[string]string, err error) {
|
||||
cur := make(map[string]string)
|
||||
key := ""
|
||||
val := ""
|
||||
inquote := false
|
||||
|
||||
pos := 0
|
||||
l := len(s)
|
||||
for i := 0; i < l; i++ {
|
||||
r := rune(s[i])
|
||||
|
||||
if inquote {
|
||||
if r == '"' {
|
||||
cur[key] = s[pos:i]
|
||||
key = ""
|
||||
pos = i
|
||||
inquote = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
switch {
|
||||
case r == '"': // start of quoted-string
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("unexpected quoted string as pos %d", i)
|
||||
}
|
||||
inquote = true
|
||||
pos = i + 1
|
||||
|
||||
case r == ';': // end of forwarded-pair
|
||||
cur[key] = s[pos:i]
|
||||
key = ""
|
||||
i = skipWS(s, i)
|
||||
pos = i + 1
|
||||
|
||||
case r == '=': // end of token
|
||||
key = strings.ToLower(strings.TrimFunc(s[pos:i], isWS))
|
||||
i = skipWS(s, i)
|
||||
pos = i + 1
|
||||
|
||||
case r == ',': // end of forwarded-element
|
||||
if key != "" {
|
||||
if val == "" {
|
||||
val = s[pos:i]
|
||||
}
|
||||
cur[key] = val
|
||||
}
|
||||
elements = append(elements, cur)
|
||||
cur = make(map[string]string)
|
||||
key = ""
|
||||
val = ""
|
||||
|
||||
i = skipWS(s, i)
|
||||
pos = i + 1
|
||||
case tchar(r) || isWS(r): // valid token character or whitespace
|
||||
continue
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid token character at pos %d: %c", i, r)
|
||||
}
|
||||
}
|
||||
|
||||
if inquote {
|
||||
return nil, fmt.Errorf("unterminated quoted-string at pos %d", len(s))
|
||||
}
|
||||
|
||||
if key != "" {
|
||||
if pos < len(s) {
|
||||
val = s[pos:]
|
||||
}
|
||||
cur[key] = val
|
||||
}
|
||||
if len(cur) > 0 {
|
||||
elements = append(elements, cur)
|
||||
}
|
||||
return elements, nil
|
||||
}
|
||||
|
||||
func tchar(r rune) bool {
|
||||
return strings.ContainsRune("!#$%&'*+-.^_`|~", r) ||
|
||||
'0' <= r && r <= '9' ||
|
||||
'a' <= r && r <= 'z' ||
|
||||
'A' <= r && r <= 'Z'
|
||||
}
|
||||
|
||||
func skipWS(s string, i int) int {
|
||||
for isWS(rune(s[i+1])) {
|
||||
i++
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
func isWS(r rune) bool {
|
||||
return strings.ContainsRune(" \t\v\r\n", r)
|
||||
}
|
86
challenge/http01/domain_matcher_test.go
Normal file
86
challenge/http01/domain_matcher_test.go
Normal file
|
@ -0,0 +1,86 @@
|
|||
package http01
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseForwardedHeader(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
input string
|
||||
want []map[string]string
|
||||
err string
|
||||
}{
|
||||
{
|
||||
name: "empty input",
|
||||
input: "",
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "simple case",
|
||||
input: `for=1.2.3.4;host=example.com; by=127.0.0.1`,
|
||||
want: []map[string]string{
|
||||
{"for": "1.2.3.4", "host": "example.com", "by": "127.0.0.1"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "quoted-string",
|
||||
input: `foo="bar"`,
|
||||
want: []map[string]string{
|
||||
{"foo": "bar"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multiple entries",
|
||||
input: `a=1, b=2; c=3, d=4`,
|
||||
want: []map[string]string{
|
||||
{"a": "1"},
|
||||
{"b": "2", "c": "3"},
|
||||
{"d": "4"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "whitespace",
|
||||
input: " a = 1,\tb\n=\r\n2,c=\" untrimmed \"",
|
||||
want: []map[string]string{
|
||||
{"a": "1"},
|
||||
{"b": "2"},
|
||||
{"c": " untrimmed "},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unterminated quote",
|
||||
input: `x="y`,
|
||||
err: "unterminated quoted-string",
|
||||
},
|
||||
{
|
||||
name: "unexpected quote",
|
||||
input: `"x=y"`,
|
||||
err: "unexpected quote",
|
||||
},
|
||||
{
|
||||
name: "invalid token",
|
||||
input: `a=b, ipv6=[fe80::1], x=y`,
|
||||
err: "invalid token character at pos 10: [",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
actual, err := parseForwardedHeader(test.input)
|
||||
if test.err == "" {
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, test.want, actual)
|
||||
} else {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), test.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
65
challenge/http01/http_challenge.go
Normal file
65
challenge/http01/http_challenge.go
Normal file
|
@ -0,0 +1,65 @@
|
|||
package http01
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error
|
||||
|
||||
// ChallengePath returns the URL path for the `http-01` challenge.
|
||||
func ChallengePath(token string) string {
|
||||
return "/.well-known/acme-challenge/" + token
|
||||
}
|
||||
|
||||
type Challenge struct {
|
||||
core *api.Core
|
||||
validate ValidateFunc
|
||||
provider challenge.Provider
|
||||
}
|
||||
|
||||
func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider) *Challenge {
|
||||
return &Challenge{
|
||||
core: core,
|
||||
validate: validate,
|
||||
provider: provider,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Challenge) SetProvider(provider challenge.Provider) {
|
||||
c.provider = provider
|
||||
}
|
||||
|
||||
func (c *Challenge) Solve(authz acme.Authorization) error {
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
log.Infof("[%s] acme: Trying to solve HTTP-01", domain)
|
||||
|
||||
chlng, err := challenge.FindChallenge(challenge.HTTP01, authz)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 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: %w", domain, err)
|
||||
}
|
||||
defer func() {
|
||||
err := c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth)
|
||||
if err != nil {
|
||||
log.Warnf("[%s] acme: cleaning up failed: %v", domain, err)
|
||||
}
|
||||
}()
|
||||
|
||||
chlng.KeyAuthorization = keyAuth
|
||||
return c.validate(c.core, domain, chlng)
|
||||
}
|
137
challenge/http01/http_challenge_server.go
Normal file
137
challenge/http01/http_challenge_server.go
Normal file
|
@ -0,0 +1,137 @@
|
|||
package http01
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
// ProviderServer implements ChallengeProvider for `http-01` challenge.
|
||||
// It may be instantiated without using the NewProviderServer function if
|
||||
// you want only to use the default values.
|
||||
type ProviderServer struct {
|
||||
address string
|
||||
network string // must be valid argument to net.Listen
|
||||
|
||||
socketMode fs.FileMode
|
||||
|
||||
matcher domainMatcher
|
||||
done chan bool
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
// NewProviderServer creates a new ProviderServer on the selected interface and port.
|
||||
// Setting iface and / or port to an empty string will make the server fall back to
|
||||
// the "any" interface and port 80 respectively.
|
||||
func NewProviderServer(iface, port string) *ProviderServer {
|
||||
if port == "" {
|
||||
port = "80"
|
||||
}
|
||||
|
||||
return &ProviderServer{network: "tcp", address: net.JoinHostPort(iface, port), matcher: &hostMatcher{}}
|
||||
}
|
||||
|
||||
func NewUnixProviderServer(socketPath string, mode fs.FileMode) *ProviderServer {
|
||||
return &ProviderServer{network: "unix", address: socketPath, socketMode: mode, matcher: &hostMatcher{}}
|
||||
}
|
||||
|
||||
// Present starts a web server and makes the token available at `ChallengePath(token)` for web requests.
|
||||
func (s *ProviderServer) Present(domain, token, keyAuth string) error {
|
||||
var err error
|
||||
s.listener, err = net.Listen(s.network, s.GetAddress())
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not start HTTP server for challenge: %w", err)
|
||||
}
|
||||
|
||||
if s.network == "unix" {
|
||||
if err = os.Chmod(s.address, s.socketMode); err != nil {
|
||||
return fmt.Errorf("chmod %s: %w", s.address, err)
|
||||
}
|
||||
}
|
||||
|
||||
s.done = make(chan bool)
|
||||
go s.serve(domain, token, keyAuth)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProviderServer) GetAddress() string {
|
||||
return s.address
|
||||
}
|
||||
|
||||
// CleanUp closes the HTTP server and removes the token from `ChallengePath(token)`.
|
||||
func (s *ProviderServer) CleanUp(domain, token, keyAuth string) error {
|
||||
if s.listener == nil {
|
||||
return nil
|
||||
}
|
||||
s.listener.Close()
|
||||
<-s.done
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetProxyHeader changes the validation of incoming requests.
|
||||
// By default, s matches the "Host" header value to the domain name.
|
||||
//
|
||||
// When the server runs behind a proxy server, this is not the correct place to look at;
|
||||
// Apache and NGINX have traditionally moved the original Host header into a new header named "X-Forwarded-Host".
|
||||
// Other webservers might use different names;
|
||||
// and RFC7239 has standardized a new header named "Forwarded" (with slightly different semantics).
|
||||
//
|
||||
// The exact behavior depends on the value of headerName:
|
||||
// - "" (the empty string) and "Host" will restore the default and only check the Host header
|
||||
// - "Forwarded" will look for a Forwarded header, and inspect it according to https://www.rfc-editor.org/rfc/rfc7239.html
|
||||
// - any other value will check the header value with the same name.
|
||||
func (s *ProviderServer) SetProxyHeader(headerName string) {
|
||||
switch h := textproto.CanonicalMIMEHeaderKey(headerName); h {
|
||||
case "", "Host":
|
||||
s.matcher = &hostMatcher{}
|
||||
case "Forwarded":
|
||||
s.matcher = &forwardedMatcher{}
|
||||
default:
|
||||
s.matcher = arbitraryMatcher(h)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProviderServer) serve(domain, token, keyAuth string) {
|
||||
path := ChallengePath(token)
|
||||
|
||||
// The incoming request will be validated to prevent DNS rebind attacks.
|
||||
// We only respond with the keyAuth, when we're receiving a GET requests with
|
||||
// the "Host" header matching the domain (the latter is configurable though SetProxyHeader).
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet && s.matcher.matches(r, domain) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
_, err := w.Write([]byte(keyAuth))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
log.Infof("[%s] Served key authentication", domain)
|
||||
} else {
|
||||
log.Warnf("Received request for domain %s with method %s but the domain did not match any challenge. Please ensure you are passing the %s header properly.", r.Host, r.Method, s.matcher.name())
|
||||
_, err := w.Write([]byte("TEST"))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
httpServer := &http.Server{Handler: mux}
|
||||
|
||||
// Once httpServer is shut down
|
||||
// we don't want any lingering connections, so disable KeepAlives.
|
||||
httpServer.SetKeepAlivesEnabled(false)
|
||||
|
||||
err := httpServer.Serve(s.listener)
|
||||
if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
|
||||
log.Println(err)
|
||||
}
|
||||
s.done <- true
|
||||
}
|
438
challenge/http01/http_challenge_test.go
Normal file
438
challenge/http01/http_challenge_test.go
Normal file
|
@ -0,0 +1,438 @@
|
|||
package http01
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestProviderServer_GetAddress(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Cleanup(func() { _ = os.RemoveAll(dir) })
|
||||
|
||||
sock := filepath.Join(dir, "var", "run", "test")
|
||||
|
||||
testCases := []struct {
|
||||
desc string
|
||||
server *ProviderServer
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
desc: "TCP default address",
|
||||
server: NewProviderServer("", ""),
|
||||
expected: ":80",
|
||||
},
|
||||
{
|
||||
desc: "TCP with explicit port",
|
||||
server: NewProviderServer("", "8080"),
|
||||
expected: ":8080",
|
||||
},
|
||||
{
|
||||
desc: "TCP with host and port",
|
||||
server: NewProviderServer("localhost", "8080"),
|
||||
expected: "localhost:8080",
|
||||
},
|
||||
{
|
||||
desc: "UDS socket",
|
||||
server: NewUnixProviderServer(sock, fs.ModeSocket|0o666),
|
||||
expected: sock,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
address := test.server.GetAddress()
|
||||
assert.Equal(t, test.expected, address)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallenge(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
providerServer := NewProviderServer("", "23457")
|
||||
|
||||
validate := func(_ *api.Core, _ string, chlng acme.Challenge) error {
|
||||
uri := "http://localhost" + providerServer.GetAddress() + ChallengePath(chlng.Token)
|
||||
|
||||
resp, err := http.DefaultClient.Get(uri)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if want := "text/plain"; resp.Header.Get("Content-Type") != want {
|
||||
t.Errorf("Get(%q) Content-Type: got %q, want %q", uri, resp.Header.Get("Content-Type"), want)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bodyStr := string(body)
|
||||
|
||||
if bodyStr != chlng.KeyAuthorization {
|
||||
t.Errorf("Get(%q) Body: got %q, want %q", uri, bodyStr, chlng.KeyAuthorization)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
solver := NewChallenge(core, validate, providerServer)
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "localhost:23457",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.HTTP01.String(), Token: "http1"},
|
||||
},
|
||||
}
|
||||
|
||||
err = solver.Solve(authz)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestChallengeUnix(t *testing.T) {
|
||||
if runtime.GOOS != "linux" {
|
||||
t.Skip("only for UNIX systems")
|
||||
}
|
||||
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
dir := t.TempDir()
|
||||
t.Cleanup(func() { _ = os.RemoveAll(dir) })
|
||||
|
||||
socket := filepath.Join(dir, "lego-challenge-test.sock")
|
||||
|
||||
providerServer := NewUnixProviderServer(socket, fs.ModeSocket|0o666)
|
||||
|
||||
validate := func(_ *api.Core, _ string, chlng acme.Challenge) error {
|
||||
// any uri will do, as we hijack the dial
|
||||
uri := "http://localhost" + ChallengePath(chlng.Token)
|
||||
|
||||
client := &http.Client{Transport: &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return net.Dial("unix", socket)
|
||||
},
|
||||
}}
|
||||
|
||||
resp, err := client.Get(uri)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if want := "text/plain"; resp.Header.Get("Content-Type") != want {
|
||||
t.Errorf("Get(%q) Content-Type: got %q, want %q", uri, resp.Header.Get("Content-Type"), want)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bodyStr := string(body)
|
||||
|
||||
if bodyStr != chlng.KeyAuthorization {
|
||||
t.Errorf("Get(%q) Body: got %q, want %q", uri, bodyStr, chlng.KeyAuthorization)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
solver := NewChallenge(core, validate, providerServer)
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "localhost",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.HTTP01.String(), Token: "http1"},
|
||||
},
|
||||
}
|
||||
|
||||
err = solver.Solve(authz)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestChallengeInvalidPort(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 128)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
validate := func(_ *api.Core, _ string, _ acme.Challenge) error { return nil }
|
||||
|
||||
solver := NewChallenge(core, validate, NewProviderServer("", "123456"))
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "localhost:123456",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.HTTP01.String(), Token: "http2"},
|
||||
},
|
||||
}
|
||||
|
||||
err = solver.Solve(authz)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid port")
|
||||
assert.Contains(t, err.Error(), "123456")
|
||||
}
|
||||
|
||||
type testProxyHeader struct {
|
||||
name string
|
||||
values []string
|
||||
}
|
||||
|
||||
func (h *testProxyHeader) update(r *http.Request) {
|
||||
if h == nil || len(h.values) == 0 {
|
||||
return
|
||||
}
|
||||
if h.name == "Host" {
|
||||
r.Host = h.values[0]
|
||||
} else if h.name != "" {
|
||||
r.Header[h.name] = h.values
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallengeWithProxy(t *testing.T) {
|
||||
h := func(name string, values ...string) *testProxyHeader {
|
||||
name = textproto.CanonicalMIMEHeaderKey(name)
|
||||
return &testProxyHeader{name, values}
|
||||
}
|
||||
|
||||
const (
|
||||
ok = "localhost:23457"
|
||||
nook = "example.com"
|
||||
)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
header *testProxyHeader
|
||||
extra *testProxyHeader
|
||||
isErr bool
|
||||
}{
|
||||
// tests for hostMatcher
|
||||
{
|
||||
name: "no proxy",
|
||||
},
|
||||
{
|
||||
name: "empty string",
|
||||
header: h(""),
|
||||
},
|
||||
{
|
||||
name: "empty Host",
|
||||
header: h("host"),
|
||||
},
|
||||
{
|
||||
name: "matching Host",
|
||||
header: h("host", ok),
|
||||
},
|
||||
{
|
||||
name: "Host mismatch",
|
||||
header: h("host", nook),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "Host mismatch (ignoring forwarding header)",
|
||||
header: h("host", nook),
|
||||
extra: h("X-Forwarded-Host", ok),
|
||||
isErr: true,
|
||||
},
|
||||
// test for arbitraryMatcher
|
||||
{
|
||||
name: "matching X-Forwarded-Host",
|
||||
header: h("X-Forwarded-Host", ok),
|
||||
},
|
||||
{
|
||||
name: "matching X-Forwarded-Host (multiple fields)",
|
||||
header: h("X-Forwarded-Host", ok, nook),
|
||||
},
|
||||
{
|
||||
name: "matching X-Forwarded-Host (chain value)",
|
||||
header: h("X-Forwarded-Host", ok+", "+nook),
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host mismatch",
|
||||
header: h("X-Forwarded-Host", nook),
|
||||
extra: h("host", ok),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-Host mismatch (multiple fields)",
|
||||
header: h("X-Forwarded-Host", nook, ok),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "matching X-Something-Else",
|
||||
header: h("X-Something-Else", ok),
|
||||
},
|
||||
{
|
||||
name: "matching X-Something-Else (multiple fields)",
|
||||
header: h("X-Something-Else", ok, nook),
|
||||
},
|
||||
{
|
||||
name: "matching X-Something-Else (chain value)",
|
||||
header: h("X-Something-Else", ok+", "+nook),
|
||||
},
|
||||
{
|
||||
name: "X-Something-Else mismatch",
|
||||
header: h("X-Something-Else", nook),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "X-Something-Else mismatch (multiple fields)",
|
||||
header: h("X-Something-Else", nook, ok),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "X-Something-Else mismatch (chain value)",
|
||||
header: h("X-Something-Else", nook+", "+ok),
|
||||
isErr: true,
|
||||
},
|
||||
// tests for forwardedHeader
|
||||
{
|
||||
name: "matching Forwarded",
|
||||
header: h("Forwarded", fmt.Sprintf("host=%q;foo=bar", ok)),
|
||||
},
|
||||
{
|
||||
name: "matching Forwarded (multiple fields)",
|
||||
header: h("Forwarded", fmt.Sprintf("host=%q", ok), "host="+nook),
|
||||
},
|
||||
{
|
||||
name: "matching Forwarded (chain value)",
|
||||
header: h("Forwarded", fmt.Sprintf("host=%q, host=%s", ok, nook)),
|
||||
},
|
||||
{
|
||||
name: "Forwarded mismatch",
|
||||
header: h("Forwarded", "host="+nook),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "Forwarded mismatch (missing information)",
|
||||
header: h("Forwarded", "for=127.0.0.1"),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "Forwarded mismatch (multiple fields)",
|
||||
header: h("Forwarded", "host="+nook, fmt.Sprintf("host=%q", ok)),
|
||||
isErr: true,
|
||||
},
|
||||
{
|
||||
name: "Forwarded mismatch (chain value)",
|
||||
header: h("Forwarded", fmt.Sprintf("host=%s, host=%q", nook, ok)),
|
||||
isErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
testServeWithProxy(t, test.header, test.extra, test.isErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testServeWithProxy(t *testing.T, header, extra *testProxyHeader, expectError bool) {
|
||||
t.Helper()
|
||||
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
providerServer := NewProviderServer("localhost", "23457")
|
||||
if header != nil {
|
||||
providerServer.SetProxyHeader(header.name)
|
||||
}
|
||||
|
||||
validate := func(_ *api.Core, _ string, chlng acme.Challenge) error {
|
||||
uri := "http://" + providerServer.GetAddress() + ChallengePath(chlng.Token)
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, uri, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
header.update(req)
|
||||
extra.update(req)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if want := "text/plain"; resp.Header.Get("Content-Type") != want {
|
||||
return fmt.Errorf("Get(%q) Content-Type: got %q, want %q", uri, resp.Header.Get("Content-Type"), want)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bodyStr := string(body)
|
||||
|
||||
if bodyStr != chlng.KeyAuthorization {
|
||||
return fmt.Errorf("Get(%q) Body: got %q, want %q", uri, bodyStr, chlng.KeyAuthorization)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
solver := NewChallenge(core, validate, providerServer)
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "localhost:23457",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.HTTP01.String(), Token: "http1"},
|
||||
},
|
||||
}
|
||||
|
||||
err = solver.Solve(authz)
|
||||
if expectError {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
125
challenge/nns01/nns_challenge.go
Normal file
125
challenge/nns01/nns_challenge.go
Normal file
|
@ -0,0 +1,125 @@
|
|||
package nns01
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error
|
||||
|
||||
// Challenge implements the nns-01 challenge.
|
||||
type Challenge struct {
|
||||
core *api.Core
|
||||
validate ValidateFunc
|
||||
provider challenge.Provider
|
||||
}
|
||||
|
||||
func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider) *Challenge {
|
||||
chlg := &Challenge{
|
||||
core: core,
|
||||
validate: validate,
|
||||
provider: provider,
|
||||
}
|
||||
|
||||
return chlg
|
||||
}
|
||||
|
||||
// PreSolve submits the txt record to the nns provider.
|
||||
func (c *Challenge) PreSolve(authz acme.Authorization) error {
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
log.Infof("[%s] acme: Preparing to solve NNS-01", domain)
|
||||
|
||||
chlng, keyAuth, err := c.getChallengeInfo(authz)
|
||||
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: %w", domain, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Challenge) Solve(authz acme.Authorization) error {
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
log.Infof("[%s] acme: Trying to solve NNS-01", domain)
|
||||
|
||||
chlng, keyAuth, err := c.getChallengeInfo(authz)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
chlng.KeyAuthorization = keyAuth
|
||||
return c.validate(c.core, domain, chlng)
|
||||
}
|
||||
|
||||
// CleanUp cleans the challenge.
|
||||
func (c *Challenge) CleanUp(authz acme.Authorization) error {
|
||||
log.Infof("[%s] acme: Cleaning NNS-01 challenge", challenge.GetTargetedDomain(authz))
|
||||
|
||||
chlng, keyAuth, err := c.getChallengeInfo(authz)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth)
|
||||
}
|
||||
|
||||
func (c *Challenge) Sequential() (bool, time.Duration) {
|
||||
if p, ok := c.provider.(sequential); ok {
|
||||
return ok, p.Sequential()
|
||||
}
|
||||
return false, 0
|
||||
}
|
||||
|
||||
type sequential interface {
|
||||
Sequential() time.Duration
|
||||
}
|
||||
|
||||
// RecordInfo contains the information use to create the TXT record.
|
||||
type RecordInfo struct {
|
||||
// FQDN is the full-qualified challenge domain (`acme-challenge.[domain]`)
|
||||
FQDN string
|
||||
// Value contains the value for the TXT record
|
||||
Value string
|
||||
}
|
||||
|
||||
// GetRecordInfo returns information used to create a TXT record which will fulfill the `nns-01` challenge.
|
||||
func GetRecordInfo(domain, keyAuth string) RecordInfo {
|
||||
keyAuthShaBytes := sha256.Sum256([]byte(keyAuth))
|
||||
// base64URL encoding without padding
|
||||
value := base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size])
|
||||
|
||||
return RecordInfo{
|
||||
Value: value,
|
||||
FQDN: getRecordFQDN(domain),
|
||||
}
|
||||
}
|
||||
|
||||
func getRecordFQDN(domain string) string {
|
||||
return fmt.Sprintf("acme-challenge.%s", domain)
|
||||
}
|
||||
|
||||
func (c *Challenge) getChallengeInfo(authz acme.Authorization) (acme.Challenge, string, error) {
|
||||
chlng, err := challenge.FindChallenge(challenge.NNS01, authz)
|
||||
if err != nil {
|
||||
return acme.Challenge{}, "", err
|
||||
}
|
||||
|
||||
// Generate the Key Authorization for the challenge
|
||||
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
|
||||
if err != nil {
|
||||
return acme.Challenge{}, "", err
|
||||
}
|
||||
|
||||
return chlng, keyAuth, nil
|
||||
}
|
171
challenge/nns01/nns_provider.go
Normal file
171
challenge/nns01/nns_provider.go
Normal file
|
@ -0,0 +1,171 @@
|
|||
package nns01
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"github.com/nspcc-dev/neo-go/cli/flags"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
)
|
||||
|
||||
// multiSchemeClient unites invoker.RPCInvoke and common interface of
|
||||
// rpcclient.Client and rpcclient.WSClient.
|
||||
type multiSchemeClient interface {
|
||||
actor.RPCActor
|
||||
actor.RPCPollingWaiter
|
||||
// Init turns client to "ready-to-work" state.
|
||||
Init() error
|
||||
// Close closes connections.
|
||||
Close()
|
||||
// GetContractStateByID returns state of the NNS contract on 1 input.
|
||||
GetContractStateByID(int32) (*state.Contract, error)
|
||||
}
|
||||
|
||||
type NNSProvider struct {
|
||||
nnsServer string
|
||||
account *wallet.Account
|
||||
nnsContract util.Uint160
|
||||
client multiSchemeClient
|
||||
}
|
||||
|
||||
// NewNNSProvider returns configured NNSProvider instance.
|
||||
func NewNNSProvider(nnsServer string, walletFile string, accountAddress string, accountPassword string) (*NNSProvider, error) {
|
||||
w, err := wallet.NewWalletFromFile(walletFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("retrieve wallet from file: %w", err)
|
||||
}
|
||||
var address util.Uint160
|
||||
if len(accountAddress) == 0 {
|
||||
address = w.GetChangeAddress()
|
||||
} else {
|
||||
address, err = flags.ParseAddress(accountAddress)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse account address: %w", err)
|
||||
}
|
||||
}
|
||||
acc := w.GetAccount(address)
|
||||
err = acc.Decrypt(accountPassword, w.Scrypt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt account: %w", err)
|
||||
}
|
||||
|
||||
provider := NNSProvider{
|
||||
nnsServer: nnsServer,
|
||||
account: acc,
|
||||
}
|
||||
return &provider, nil
|
||||
}
|
||||
|
||||
// dial connects to the address of the NNS server.
|
||||
// If URL address scheme is 'ws' or 'wss', then WebSocket protocol is used, otherwise HTTP.
|
||||
func (n *NNSProvider) dial() error {
|
||||
var err error
|
||||
|
||||
uri, err := url.Parse(n.nnsServer)
|
||||
if err == nil && (uri.Scheme == "ws" || uri.Scheme == "wss") {
|
||||
// WSOptions not in package `github.com/nspcc-dev/neo-go v0.101.3`
|
||||
n.client, err = rpcclient.NewWS(context.Background(), n.nnsServer, rpcclient.Options{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create Neo WebSocket client: %w", err)
|
||||
}
|
||||
} else {
|
||||
n.client, err = rpcclient.New(context.Background(), n.nnsServer, rpcclient.Options{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create Neo HTTP client: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err = n.client.Init(); err != nil {
|
||||
return fmt.Errorf("initialize Neo client: %w", err)
|
||||
}
|
||||
|
||||
nnsContract, err := n.client.GetContractStateByID(1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get NNS contract state: %w", err)
|
||||
}
|
||||
|
||||
n.nnsContract = nnsContract.Hash
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes connections of multiSchemeClient.
|
||||
func (n *NNSProvider) close() {
|
||||
if n.client != nil {
|
||||
n.client.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Present creates a TXT record using the specified parameters to fulfill the nns-01 challenge.
|
||||
// It implements Provider interface in order to use NNSProvider as Provider.
|
||||
func (n *NNSProvider) Present(domain, _, keyAuth string) error {
|
||||
err := n.dial()
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect to the NNS server: %w", err)
|
||||
}
|
||||
|
||||
act, err := actor.NewSimple(n.client, n.account)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create actor: %w", err)
|
||||
}
|
||||
|
||||
info := GetRecordInfo(domain, keyAuth)
|
||||
err = n.addTXTRecord(act, info.FQDN, info.Value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("add txt record: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// addTXTRecord adds a new TXT record with the specified data to the provided domain by calling `addRecord` method
|
||||
// of NNS contract.
|
||||
func (n *NNSProvider) addTXTRecord(act *actor.Actor, name string, data string) error {
|
||||
waiter, err := actor.NewPollingWaiter(n.client)
|
||||
if err != nil {
|
||||
return fmt.Errorf("waiter creation: %w", err)
|
||||
}
|
||||
_, err = waiter.Wait(act.SendCall(n.nnsContract, "addRecord", name, int64(nns.TXT), data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("contract invocation: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanUp removes the TXT record matching the specified parameters.
|
||||
// It implements Provider interface in order to use NNSProvider as Provider.
|
||||
func (n *NNSProvider) CleanUp(domain, _, keyAuth string) error {
|
||||
defer n.close()
|
||||
|
||||
act, err := actor.NewSimple(n.client, n.account)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create actor: %w", err)
|
||||
}
|
||||
|
||||
info := GetRecordInfo(domain, keyAuth)
|
||||
err = n.deleteTXTRecords(act, info.FQDN)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete txt records: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteTXTRecords removes TXT records from the provided domain by calling `deleteRecords` method of NNS contract.
|
||||
func (n *NNSProvider) deleteTXTRecords(act *actor.Actor, name string) error {
|
||||
waiter, err := actor.NewPollingWaiter(n.client)
|
||||
if err != nil {
|
||||
return fmt.Errorf("waiter creation: %w", err)
|
||||
}
|
||||
_, err = waiter.Wait(act.SendCall(n.nnsContract, "deleteRecords", name, int64(nns.TXT)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("contract invocation: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
28
challenge/provider.go
Normal file
28
challenge/provider.go
Normal file
|
@ -0,0 +1,28 @@
|
|||
package challenge
|
||||
|
||||
import "time"
|
||||
|
||||
// Provider enables implementing a custom challenge
|
||||
// provider. Present presents the solution to a challenge available to
|
||||
// be solved. CleanUp will be called by the challenge if Present ends
|
||||
// in a non-error state.
|
||||
type Provider interface {
|
||||
Present(domain, token, keyAuth string) error
|
||||
CleanUp(domain, token, keyAuth string) error
|
||||
}
|
||||
|
||||
// ProviderTimeout allows for implementing a
|
||||
// Provider where an unusually long timeout is required when
|
||||
// waiting for an ACME challenge to be satisfied, such as when
|
||||
// checking for DNS record propagation. If an implementor of a
|
||||
// Provider provides a Timeout method, then the return values
|
||||
// of the Timeout method will be used when appropriate by the acme
|
||||
// package. The interval value is the time between checks.
|
||||
//
|
||||
// The default values used for timeout and interval are 60 seconds and
|
||||
// 2 seconds respectively. These are used when no Timeout method is
|
||||
// defined for the Provider.
|
||||
type ProviderTimeout interface {
|
||||
Provider
|
||||
Timeout() (timeout, interval time.Duration)
|
||||
}
|
25
challenge/resolver/errors.go
Normal file
25
challenge/resolver/errors.go
Normal file
|
@ -0,0 +1,25 @@
|
|||
package resolver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// obtainError is returned when there are specific errors available per domain.
|
||||
type obtainError map[string]error
|
||||
|
||||
func (e obtainError) Error() string {
|
||||
buffer := bytes.NewBufferString("error: one or more domains had a problem:\n")
|
||||
|
||||
var domains []string
|
||||
for domain := range e {
|
||||
domains = append(domains, domain)
|
||||
}
|
||||
sort.Strings(domains)
|
||||
|
||||
for _, domain := range domains {
|
||||
_, _ = fmt.Fprintf(buffer, "[%s] %s\n", domain, e[domain])
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
173
challenge/resolver/prober.go
Normal file
173
challenge/resolver/prober.go
Normal file
|
@ -0,0 +1,173 @@
|
|||
package resolver
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
// Interface for all challenge solvers to implement.
|
||||
type solver interface {
|
||||
Solve(authorization acme.Authorization) error
|
||||
}
|
||||
|
||||
// Interface for challenges like dns, where we can set a record in advance for ALL challenges.
|
||||
// This saves quite a bit of time vs creating the records and solving them serially.
|
||||
type preSolver interface {
|
||||
PreSolve(authorization acme.Authorization) error
|
||||
}
|
||||
|
||||
// Interface for challenges like dns, where we can solve all the challenges before to delete them.
|
||||
type cleanup interface {
|
||||
CleanUp(authorization acme.Authorization) error
|
||||
}
|
||||
|
||||
type sequential interface {
|
||||
Sequential() (bool, time.Duration)
|
||||
}
|
||||
|
||||
// an authz with the solver we have chosen and the index of the challenge associated with it.
|
||||
type selectedAuthSolver struct {
|
||||
authz acme.Authorization
|
||||
solver solver
|
||||
}
|
||||
|
||||
type Prober struct {
|
||||
solverManager *SolverManager
|
||||
}
|
||||
|
||||
func NewProber(solverManager *SolverManager) *Prober {
|
||||
return &Prober{
|
||||
solverManager: solverManager,
|
||||
}
|
||||
}
|
||||
|
||||
// Solve Looks through the challenge combinations to find a solvable match.
|
||||
// Then solves the challenges in series and returns.
|
||||
func (p *Prober) Solve(authorizations []acme.Authorization) error {
|
||||
failures := make(obtainError)
|
||||
|
||||
var authSolvers []*selectedAuthSolver
|
||||
var authSolversSequential []*selectedAuthSolver
|
||||
|
||||
// Loop through the resources, basically through the domains.
|
||||
// First pass just selects a solver for each authz.
|
||||
for _, authz := range authorizations {
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
if authz.Status == acme.StatusValid {
|
||||
// Boulder might recycle recent validated authz (see issue #267)
|
||||
log.Infof("[%s] acme: authorization already valid; skipping challenge", domain)
|
||||
continue
|
||||
}
|
||||
|
||||
if solvr := p.solverManager.chooseSolver(authz); solvr != nil {
|
||||
authSolver := &selectedAuthSolver{authz: authz, solver: solvr}
|
||||
|
||||
switch s := solvr.(type) {
|
||||
case sequential:
|
||||
if ok, _ := s.Sequential(); ok {
|
||||
authSolversSequential = append(authSolversSequential, authSolver)
|
||||
} else {
|
||||
authSolvers = append(authSolvers, authSolver)
|
||||
}
|
||||
default:
|
||||
authSolvers = append(authSolvers, authSolver)
|
||||
}
|
||||
} else {
|
||||
failures[domain] = fmt.Errorf("[%s] acme: could not determine solvers", domain)
|
||||
}
|
||||
}
|
||||
|
||||
parallelSolve(authSolvers, failures)
|
||||
|
||||
sequentialSolve(authSolversSequential, failures)
|
||||
|
||||
// Be careful not to return an empty failures map,
|
||||
// for even an empty obtainError is a non-nil error value
|
||||
if len(failures) > 0 {
|
||||
return failures
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sequentialSolve(authSolvers []*selectedAuthSolver, failures obtainError) {
|
||||
for i, authSolver := range authSolvers {
|
||||
// Submit the challenge
|
||||
domain := challenge.GetTargetedDomain(authSolver.authz)
|
||||
|
||||
if solvr, ok := authSolver.solver.(preSolver); ok {
|
||||
err := solvr.PreSolve(authSolver.authz)
|
||||
if err != nil {
|
||||
failures[domain] = err
|
||||
cleanUp(authSolver.solver, authSolver.authz)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Solve challenge
|
||||
err := authSolver.solver.Solve(authSolver.authz)
|
||||
if err != nil {
|
||||
failures[domain] = err
|
||||
cleanUp(authSolver.solver, authSolver.authz)
|
||||
continue
|
||||
}
|
||||
|
||||
// Clean challenge
|
||||
cleanUp(authSolver.solver, authSolver.authz)
|
||||
|
||||
if len(authSolvers)-1 > i {
|
||||
solvr := authSolver.solver.(sequential)
|
||||
_, interval := solvr.Sequential()
|
||||
log.Infof("sequence: wait for %s", interval)
|
||||
time.Sleep(interval)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parallelSolve(authSolvers []*selectedAuthSolver, failures obtainError) {
|
||||
// For all valid preSolvers, first submit the challenges so they have max time to propagate
|
||||
for _, authSolver := range authSolvers {
|
||||
authz := authSolver.authz
|
||||
if solvr, ok := authSolver.solver.(preSolver); ok {
|
||||
err := solvr.PreSolve(authz)
|
||||
if err != nil {
|
||||
failures[challenge.GetTargetedDomain(authz)] = err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
defer func() {
|
||||
// Clean all created TXT records
|
||||
for _, authSolver := range authSolvers {
|
||||
cleanUp(authSolver.solver, authSolver.authz)
|
||||
}
|
||||
}()
|
||||
|
||||
// Finally solve all challenges for real
|
||||
for _, authSolver := range authSolvers {
|
||||
authz := authSolver.authz
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
if failures[domain] != nil {
|
||||
// already failed in previous loop
|
||||
continue
|
||||
}
|
||||
|
||||
err := authSolver.solver.Solve(authz)
|
||||
if err != nil {
|
||||
failures[domain] = err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cleanUp(solvr solver, authz acme.Authorization) {
|
||||
if solvr, ok := solvr.(cleanup); ok {
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
err := solvr.CleanUp(authz)
|
||||
if err != nil {
|
||||
log.Warnf("[%s] acme: cleaning up failed: %v ", domain, err)
|
||||
}
|
||||
}
|
||||
}
|
44
challenge/resolver/prober_mock_test.go
Normal file
44
challenge/resolver/prober_mock_test.go
Normal file
|
@ -0,0 +1,44 @@
|
|||
package resolver
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
)
|
||||
|
||||
type preSolverMock struct {
|
||||
preSolve map[string]error
|
||||
solve map[string]error
|
||||
cleanUp map[string]error
|
||||
}
|
||||
|
||||
func (s *preSolverMock) PreSolve(authorization acme.Authorization) error {
|
||||
return s.preSolve[authorization.Identifier.Value]
|
||||
}
|
||||
|
||||
func (s *preSolverMock) Solve(authorization acme.Authorization) error {
|
||||
return s.solve[authorization.Identifier.Value]
|
||||
}
|
||||
|
||||
func (s *preSolverMock) CleanUp(authorization acme.Authorization) error {
|
||||
return s.cleanUp[authorization.Identifier.Value]
|
||||
}
|
||||
|
||||
func createStubAuthorizationHTTP01(domain, status string) acme.Authorization {
|
||||
return acme.Authorization{
|
||||
Status: status,
|
||||
Expires: time.Now(),
|
||||
Identifier: acme.Identifier{
|
||||
Type: challenge.HTTP01.String(),
|
||||
Value: domain,
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{
|
||||
Type: challenge.HTTP01.String(),
|
||||
Validated: time.Now(),
|
||||
Error: nil,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
118
challenge/resolver/prober_test.go
Normal file
118
challenge/resolver/prober_test.go
Normal file
|
@ -0,0 +1,118 @@
|
|||
package resolver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestProber_Solve(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
solvers map[challenge.Type]solver
|
||||
authz []acme.Authorization
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
desc: "success",
|
||||
solvers: map[challenge.Type]solver{
|
||||
challenge.HTTP01: &preSolverMock{
|
||||
preSolve: map[string]error{},
|
||||
solve: map[string]error{},
|
||||
cleanUp: map[string]error{},
|
||||
},
|
||||
},
|
||||
authz: []acme.Authorization{
|
||||
createStubAuthorizationHTTP01("acme.wtf", acme.StatusProcessing),
|
||||
createStubAuthorizationHTTP01("lego.wtf", acme.StatusProcessing),
|
||||
createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusProcessing),
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "already valid",
|
||||
solvers: map[challenge.Type]solver{
|
||||
challenge.HTTP01: &preSolverMock{
|
||||
preSolve: map[string]error{},
|
||||
solve: map[string]error{},
|
||||
cleanUp: map[string]error{},
|
||||
},
|
||||
},
|
||||
authz: []acme.Authorization{
|
||||
createStubAuthorizationHTTP01("acme.wtf", acme.StatusValid),
|
||||
createStubAuthorizationHTTP01("lego.wtf", acme.StatusValid),
|
||||
createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusValid),
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "when preSolve fail, auth is flagged as error and skipped",
|
||||
solvers: map[challenge.Type]solver{
|
||||
challenge.HTTP01: &preSolverMock{
|
||||
preSolve: map[string]error{
|
||||
"acme.wtf": errors.New("preSolve error acme.wtf"),
|
||||
},
|
||||
solve: map[string]error{
|
||||
"acme.wtf": errors.New("solve error acme.wtf"),
|
||||
},
|
||||
cleanUp: map[string]error{
|
||||
"acme.wtf": errors.New("clean error acme.wtf"),
|
||||
},
|
||||
},
|
||||
},
|
||||
authz: []acme.Authorization{
|
||||
createStubAuthorizationHTTP01("acme.wtf", acme.StatusProcessing),
|
||||
createStubAuthorizationHTTP01("lego.wtf", acme.StatusProcessing),
|
||||
createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusProcessing),
|
||||
},
|
||||
expectedError: `error: one or more domains had a problem:
|
||||
[acme.wtf] preSolve error acme.wtf
|
||||
`,
|
||||
},
|
||||
{
|
||||
desc: "errors at different stages",
|
||||
solvers: map[challenge.Type]solver{
|
||||
challenge.HTTP01: &preSolverMock{
|
||||
preSolve: map[string]error{
|
||||
"acme.wtf": errors.New("preSolve error acme.wtf"),
|
||||
},
|
||||
solve: map[string]error{
|
||||
"acme.wtf": errors.New("solve error acme.wtf"),
|
||||
"lego.wtf": errors.New("solve error lego.wtf"),
|
||||
},
|
||||
cleanUp: map[string]error{
|
||||
"mydomain.wtf": errors.New("clean error mydomain.wtf"),
|
||||
},
|
||||
},
|
||||
},
|
||||
authz: []acme.Authorization{
|
||||
createStubAuthorizationHTTP01("acme.wtf", acme.StatusProcessing),
|
||||
createStubAuthorizationHTTP01("lego.wtf", acme.StatusProcessing),
|
||||
createStubAuthorizationHTTP01("mydomain.wtf", acme.StatusProcessing),
|
||||
},
|
||||
expectedError: `error: one or more domains had a problem:
|
||||
[acme.wtf] preSolve error acme.wtf
|
||||
[lego.wtf] solve error lego.wtf
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
prober := &Prober{
|
||||
solverManager: &SolverManager{solvers: test.solvers},
|
||||
}
|
||||
|
||||
err := prober.Solve(test.authz)
|
||||
if test.expectedError != "" {
|
||||
require.EqualError(t, err, test.expectedError)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
171
challenge/resolver/solver_manager.go
Normal file
171
challenge/resolver/solver_manager.go
Normal file
|
@ -0,0 +1,171 @@
|
|||
package resolver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/cenkalti/backoff/v4"
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/challenge/dns01"
|
||||
"github.com/go-acme/lego/v4/challenge/http01"
|
||||
"github.com/go-acme/lego/v4/challenge/nns01"
|
||||
"github.com/go-acme/lego/v4/challenge/tlsalpn01"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
type byType []acme.Challenge
|
||||
|
||||
func (a byType) Len() int { return len(a) }
|
||||
func (a byType) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
func (a byType) Less(i, j int) bool { return a[i].Type > a[j].Type }
|
||||
|
||||
type SolverManager struct {
|
||||
core *api.Core
|
||||
solvers map[challenge.Type]solver
|
||||
}
|
||||
|
||||
func NewSolversManager(core *api.Core) *SolverManager {
|
||||
return &SolverManager{
|
||||
solvers: map[challenge.Type]solver{},
|
||||
core: core,
|
||||
}
|
||||
}
|
||||
|
||||
// SetHTTP01Provider specifies a custom provider p that can solve the given HTTP-01 challenge.
|
||||
func (c *SolverManager) SetHTTP01Provider(p challenge.Provider) error {
|
||||
c.solvers[challenge.HTTP01] = http01.NewChallenge(c.core, validate, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetTLSALPN01Provider specifies a custom provider p that can solve the given TLS-ALPN-01 challenge.
|
||||
func (c *SolverManager) SetTLSALPN01Provider(p challenge.Provider) error {
|
||||
c.solvers[challenge.TLSALPN01] = tlsalpn01.NewChallenge(c.core, validate, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDNS01Provider specifies a custom provider p that can solve the given DNS-01 challenge.
|
||||
func (c *SolverManager) SetDNS01Provider(p challenge.Provider, opts ...dns01.ChallengeOption) error {
|
||||
c.solvers[challenge.DNS01] = dns01.NewChallenge(c.core, validate, p, opts...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetNNS01Provider specifies a custom provider p that can solve the given NNS-01 challenge.
|
||||
func (c *SolverManager) SetNNS01Provider(p challenge.Provider) error {
|
||||
c.solvers[challenge.NNS01] = nns01.NewChallenge(c.core, validate, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove removes a challenge type from the available solvers.
|
||||
func (c *SolverManager) Remove(chlgType challenge.Type) {
|
||||
delete(c.solvers, chlgType)
|
||||
}
|
||||
|
||||
// Checks all challenges from the server in order and returns the first matching solver.
|
||||
func (c *SolverManager) chooseSolver(authz acme.Authorization) solver {
|
||||
// Allow to have a deterministic challenge order
|
||||
sort.Sort(byType(authz.Challenges))
|
||||
|
||||
domain := challenge.GetTargetedDomain(authz)
|
||||
for _, chlg := range authz.Challenges {
|
||||
if solvr, ok := c.solvers[challenge.Type(chlg.Type)]; ok {
|
||||
log.Infof("[%s] acme: use %s solver", domain, chlg.Type)
|
||||
return solvr
|
||||
}
|
||||
log.Infof("[%s] acme: Could not find solver for: %s", domain, chlg.Type)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validate(core *api.Core, domain string, chlg acme.Challenge) error {
|
||||
chlng, err := core.Challenges.New(chlg.URL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initiate challenge: %w", err)
|
||||
}
|
||||
|
||||
valid, err := checkChallengeStatus(chlng)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if valid {
|
||||
log.Infof("[%s] The server validated our request", domain)
|
||||
return nil
|
||||
}
|
||||
|
||||
ra, err := strconv.Atoi(chlng.RetryAfter)
|
||||
if err != nil {
|
||||
// The ACME server MUST return a Retry-After.
|
||||
// If it doesn't, we'll just poll hard.
|
||||
// Boulder does not implement the ability to retry challenges or the Retry-After header.
|
||||
// https://github.com/letsencrypt/boulder/blob/master/docs/acme-divergences.md#section-82
|
||||
ra = 5
|
||||
}
|
||||
initialInterval := time.Duration(ra) * time.Second
|
||||
|
||||
bo := backoff.NewExponentialBackOff()
|
||||
bo.InitialInterval = initialInterval
|
||||
bo.MaxInterval = 10 * initialInterval
|
||||
bo.MaxElapsedTime = 100 * initialInterval
|
||||
|
||||
// After the path is sent, the ACME server will access our server.
|
||||
// Repeatedly check the server for an updated status on our request.
|
||||
operation := func() error {
|
||||
authz, err := core.Authorizations.Get(chlng.AuthorizationURL)
|
||||
if err != nil {
|
||||
return backoff.Permanent(err)
|
||||
}
|
||||
|
||||
valid, err := checkAuthorizationStatus(authz)
|
||||
if err != nil {
|
||||
return backoff.Permanent(err)
|
||||
}
|
||||
|
||||
if valid {
|
||||
log.Infof("[%s] The server validated our request", domain)
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("the server didn't respond to our request")
|
||||
}
|
||||
|
||||
return backoff.Retry(operation, bo)
|
||||
}
|
||||
|
||||
func checkChallengeStatus(chlng acme.ExtendedChallenge) (bool, error) {
|
||||
switch chlng.Status {
|
||||
case acme.StatusValid:
|
||||
return true, nil
|
||||
case acme.StatusPending, acme.StatusProcessing:
|
||||
return false, nil
|
||||
case acme.StatusInvalid:
|
||||
return false, chlng.Error
|
||||
default:
|
||||
return false, errors.New("the server returned an unexpected state")
|
||||
}
|
||||
}
|
||||
|
||||
func checkAuthorizationStatus(authz acme.Authorization) (bool, error) {
|
||||
switch authz.Status {
|
||||
case acme.StatusValid:
|
||||
return true, nil
|
||||
case acme.StatusPending, acme.StatusProcessing:
|
||||
return false, nil
|
||||
case acme.StatusDeactivated, acme.StatusExpired, acme.StatusRevoked:
|
||||
return false, fmt.Errorf("the authorization state %s", authz.Status)
|
||||
case acme.StatusInvalid:
|
||||
for _, chlg := range authz.Challenges {
|
||||
if chlg.Status == acme.StatusInvalid && chlg.Error != nil {
|
||||
return false, chlg.Error
|
||||
}
|
||||
}
|
||||
return false, fmt.Errorf("the authorization state %s", authz.Status)
|
||||
default:
|
||||
return false, errors.New("the server returned an unexpected state")
|
||||
}
|
||||
}
|
178
challenge/resolver/solver_manager_test.go
Normal file
178
challenge/resolver/solver_manager_test.go
Normal file
|
@ -0,0 +1,178 @@
|
|||
package resolver
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/go-jose/go-jose/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestByType(t *testing.T) {
|
||||
challenges := []acme.Challenge{
|
||||
{Type: "dns-01"}, {Type: "tlsalpn-01"}, {Type: "http-01"},
|
||||
}
|
||||
|
||||
sort.Sort(byType(challenges))
|
||||
|
||||
expected := []acme.Challenge{
|
||||
{Type: "tlsalpn-01"}, {Type: "http-01"}, {Type: "dns-01"},
|
||||
}
|
||||
|
||||
assert.Equal(t, expected, challenges)
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
mux, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
var statuses []string
|
||||
|
||||
privateKey, _ := rsa.GenerateKey(rand.Reader, 512)
|
||||
|
||||
mux.HandleFunc("/chlg", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := validateNoBody(privateKey, r); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Link", "<"+apiURL+`/my-authz>; rel="up"`)
|
||||
|
||||
st := statuses[0]
|
||||
statuses = statuses[1:]
|
||||
|
||||
chlg := &acme.Challenge{Type: "http-01", Status: st, URL: "http://example.com/", Token: "token"}
|
||||
if st == acme.StatusInvalid {
|
||||
chlg.Error = &acme.ProblemDetails{}
|
||||
}
|
||||
|
||||
err := tester.WriteJSONResponse(w, chlg)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
mux.HandleFunc("/my-authz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
st := statuses[0]
|
||||
statuses = statuses[1:]
|
||||
|
||||
authorization := acme.Authorization{
|
||||
Status: st,
|
||||
Challenges: []acme.Challenge{},
|
||||
}
|
||||
|
||||
if st == acme.StatusInvalid {
|
||||
chlg := acme.Challenge{
|
||||
Status: acme.StatusInvalid,
|
||||
Error: &acme.ProblemDetails{},
|
||||
}
|
||||
authorization.Challenges = append(authorization.Challenges, chlg)
|
||||
}
|
||||
|
||||
err := tester.WriteJSONResponse(w, authorization)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
statuses []string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "POST-unexpected",
|
||||
statuses: []string{"weird"},
|
||||
want: "unexpected",
|
||||
},
|
||||
{
|
||||
name: "POST-valid",
|
||||
statuses: []string{acme.StatusValid},
|
||||
},
|
||||
{
|
||||
name: "POST-invalid",
|
||||
statuses: []string{acme.StatusInvalid},
|
||||
want: "error",
|
||||
},
|
||||
{
|
||||
name: "POST-pending-unexpected",
|
||||
statuses: []string{acme.StatusPending, "weird"},
|
||||
want: "unexpected",
|
||||
},
|
||||
{
|
||||
name: "POST-pending-valid",
|
||||
statuses: []string{acme.StatusPending, acme.StatusValid},
|
||||
},
|
||||
{
|
||||
name: "POST-pending-invalid",
|
||||
statuses: []string{acme.StatusPending, acme.StatusInvalid},
|
||||
want: "error",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
statuses = test.statuses
|
||||
|
||||
err := validate(core, "example.com", acme.Challenge{Type: "http-01", Token: "token", URL: apiURL + "/chlg"})
|
||||
if test.want == "" {
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// validateNoBody reads the http.Request POST body, parses the JWS and validates it to read the body.
|
||||
// If there is an error doing this,
|
||||
// or if the JWS body is not the empty JSON payload "{}" or a POST-as-GET payload "" an error is returned.
|
||||
// We use this to verify challenge POSTs to the ts below do not send a JWS body.
|
||||
func validateNoBody(privateKey *rsa.PrivateKey, r *http.Request) error {
|
||||
reqBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
jws, err := jose.ParseSigned(string(reqBody))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
body, err := jws.Verify(&jose.JSONWebKey{
|
||||
Key: privateKey.Public(),
|
||||
Algorithm: "RSA",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if bodyStr := string(body); bodyStr != "{}" && bodyStr != "" {
|
||||
return fmt.Errorf(`expected JWS POST body "{}" or "", got %q`, bodyStr)
|
||||
}
|
||||
return nil
|
||||
}
|
129
challenge/tlsalpn01/tls_alpn_challenge.go
Normal file
129
challenge/tlsalpn01/tls_alpn_challenge.go
Normal file
|
@ -0,0 +1,129 @@
|
|||
package tlsalpn01
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/asn1"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
// idPeAcmeIdentifierV1 is the SMI Security for PKIX Certification Extension OID referencing the ACME extension.
|
||||
// Reference: https://www.rfc-editor.org/rfc/rfc8737.html#section-6.1
|
||||
var idPeAcmeIdentifierV1 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
|
||||
|
||||
type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error
|
||||
|
||||
type Challenge struct {
|
||||
core *api.Core
|
||||
validate ValidateFunc
|
||||
provider challenge.Provider
|
||||
}
|
||||
|
||||
func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider) *Challenge {
|
||||
return &Challenge{
|
||||
core: core,
|
||||
validate: validate,
|
||||
provider: provider,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Challenge) SetProvider(provider challenge.Provider) {
|
||||
c.provider = provider
|
||||
}
|
||||
|
||||
// Solve manages the provider to validate and solve the challenge.
|
||||
func (c *Challenge) Solve(authz acme.Authorization) error {
|
||||
domain := authz.Identifier.Value
|
||||
log.Infof("[%s] acme: Trying to solve TLS-ALPN-01", challenge.GetTargetedDomain(authz))
|
||||
|
||||
chlng, err := challenge.FindChallenge(challenge.TLSALPN01, authz)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Generate the Key Authorization for the challenge
|
||||
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = c.provider.Present(domain, chlng.Token, keyAuth)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%s] acme: error presenting token: %w", challenge.GetTargetedDomain(authz), err)
|
||||
}
|
||||
defer func() {
|
||||
err := c.provider.CleanUp(domain, chlng.Token, keyAuth)
|
||||
if err != nil {
|
||||
log.Warnf("[%s] acme: cleaning up failed: %v", challenge.GetTargetedDomain(authz), err)
|
||||
}
|
||||
}()
|
||||
|
||||
chlng.KeyAuthorization = keyAuth
|
||||
return c.validate(c.core, domain, chlng)
|
||||
}
|
||||
|
||||
// ChallengeBlocks returns PEM blocks (certPEMBlock, keyPEMBlock) with the acmeValidation-v1 extension
|
||||
// and domain name for the `tls-alpn-01` challenge.
|
||||
func ChallengeBlocks(domain, keyAuth string) ([]byte, []byte, error) {
|
||||
// Compute the SHA-256 digest of the key authorization.
|
||||
zBytes := sha256.Sum256([]byte(keyAuth))
|
||||
|
||||
value, err := asn1.Marshal(zBytes[:sha256.Size])
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Add the keyAuth digest as the acmeValidation-v1 extension
|
||||
// (marked as critical such that it won't be used by non-ACME software).
|
||||
// Reference: https://www.rfc-editor.org/rfc/rfc8737.html#section-3
|
||||
extensions := []pkix.Extension{
|
||||
{
|
||||
Id: idPeAcmeIdentifierV1,
|
||||
Critical: true,
|
||||
Value: value,
|
||||
},
|
||||
}
|
||||
|
||||
// Generate a new RSA key for the certificates.
|
||||
tempPrivateKey, err := certcrypto.GeneratePrivateKey(certcrypto.RSA2048)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
rsaPrivateKey := tempPrivateKey.(*rsa.PrivateKey)
|
||||
|
||||
// Generate the PEM certificate using the provided private key, domain, and extra extensions.
|
||||
tempCertPEM, err := certcrypto.GeneratePemCert(rsaPrivateKey, domain, extensions)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Encode the private key into a PEM format. We'll need to use it to generate the x509 keypair.
|
||||
rsaPrivatePEM := certcrypto.PEMEncode(rsaPrivateKey)
|
||||
|
||||
return tempCertPEM, rsaPrivatePEM, nil
|
||||
}
|
||||
|
||||
// ChallengeCert returns a certificate with the acmeValidation-v1 extension
|
||||
// and domain name for the `tls-alpn-01` challenge.
|
||||
func ChallengeCert(domain, keyAuth string) (*tls.Certificate, error) {
|
||||
tempCertPEM, rsaPrivatePEM, err := ChallengeBlocks(domain, keyAuth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cert, err := tls.X509KeyPair(tempCertPEM, rsaPrivatePEM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &cert, nil
|
||||
}
|
96
challenge/tlsalpn01/tls_alpn_challenge_server.go
Normal file
96
challenge/tlsalpn01/tls_alpn_challenge_server.go
Normal file
|
@ -0,0 +1,96 @@
|
|||
package tlsalpn01
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
)
|
||||
|
||||
const (
|
||||
// ACMETLS1Protocol is the ALPN Protocol ID for the ACME-TLS/1 Protocol.
|
||||
ACMETLS1Protocol = "acme-tls/1"
|
||||
|
||||
// defaultTLSPort is the port that the ProviderServer will default to
|
||||
// when no other port is provided.
|
||||
defaultTLSPort = "443"
|
||||
)
|
||||
|
||||
// ProviderServer implements ChallengeProvider for `TLS-ALPN-01` challenge.
|
||||
// It may be instantiated without using the NewProviderServer
|
||||
// if you want only to use the default values.
|
||||
type ProviderServer struct {
|
||||
iface string
|
||||
port string
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
// NewProviderServer creates a new ProviderServer on the selected interface and port.
|
||||
// Setting iface and / or port to an empty string will make the server fall back to
|
||||
// the "any" interface and port 443 respectively.
|
||||
func NewProviderServer(iface, port string) *ProviderServer {
|
||||
return &ProviderServer{iface: iface, port: port}
|
||||
}
|
||||
|
||||
func (s *ProviderServer) GetAddress() string {
|
||||
return net.JoinHostPort(s.iface, s.port)
|
||||
}
|
||||
|
||||
// Present generates a certificate with a SHA-256 digest of the keyAuth provided
|
||||
// as the acmeValidation-v1 extension value to conform to the ACME-TLS-ALPN spec.
|
||||
func (s *ProviderServer) Present(domain, token, keyAuth string) error {
|
||||
if s.port == "" {
|
||||
// Fallback to port 443 if the port was not provided.
|
||||
s.port = defaultTLSPort
|
||||
}
|
||||
|
||||
// Generate the challenge certificate using the provided keyAuth and domain.
|
||||
cert, err := ChallengeCert(domain, keyAuth)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Place the generated certificate with the extension into the TLS config
|
||||
// so that it can serve the correct details.
|
||||
tlsConf := new(tls.Config)
|
||||
tlsConf.Certificates = []tls.Certificate{*cert}
|
||||
|
||||
// We must set that the `acme-tls/1` application level protocol is supported
|
||||
// so that the protocol negotiation can succeed. Reference:
|
||||
// https://www.rfc-editor.org/rfc/rfc8737.html#section-6.2
|
||||
tlsConf.NextProtos = []string{ACMETLS1Protocol}
|
||||
|
||||
// Create the listener with the created tls.Config.
|
||||
s.listener, err = tls.Listen("tcp", s.GetAddress(), tlsConf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not start HTTPS server for challenge: %w", err)
|
||||
}
|
||||
|
||||
// Shut the server down when we're finished.
|
||||
go func() {
|
||||
err := http.Serve(s.listener, nil)
|
||||
if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
|
||||
log.Println(err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanUp closes the HTTPS server.
|
||||
func (s *ProviderServer) CleanUp(domain, token, keyAuth string) error {
|
||||
if s.listener == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Server was created, close it.
|
||||
if err := s.listener.Close(); err != nil && errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
193
challenge/tlsalpn01/tls_alpn_challenge_test.go
Normal file
193
challenge/tlsalpn01/tls_alpn_challenge_test.go
Normal file
|
@ -0,0 +1,193 @@
|
|||
package tlsalpn01
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"crypto/tls"
|
||||
"encoding/asn1"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/challenge"
|
||||
"github.com/go-acme/lego/v4/platform/tester"
|
||||
"github.com/miekg/dns"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestChallenge(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
domain := "localhost"
|
||||
port := "23457"
|
||||
|
||||
mockValidate := func(_ *api.Core, _ string, chlng acme.Challenge) error {
|
||||
conn, err := tls.Dial("tcp", net.JoinHostPort(domain, port), &tls.Config{
|
||||
ServerName: domain,
|
||||
InsecureSkipVerify: true,
|
||||
})
|
||||
require.NoError(t, err, "Expected to connect to challenge server without an error")
|
||||
|
||||
// Expect the server to only return one certificate
|
||||
connState := conn.ConnectionState()
|
||||
assert.Len(t, connState.PeerCertificates, 1, "Expected the challenge server to return exactly one certificate")
|
||||
|
||||
remoteCert := connState.PeerCertificates[0]
|
||||
assert.Len(t, remoteCert.DNSNames, 1, "Expected the challenge certificate to have exactly one DNSNames entry")
|
||||
assert.Equal(t, domain, remoteCert.DNSNames[0], "challenge certificate DNSName ")
|
||||
assert.NotEmpty(t, remoteCert.Extensions, "Expected the challenge certificate to contain extensions")
|
||||
|
||||
idx := -1
|
||||
for i, ext := range remoteCert.Extensions {
|
||||
if idPeAcmeIdentifierV1.Equal(ext.Id) {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
require.NotEqual(t, -1, idx, "Expected the challenge certificate to contain an extension with the id-pe-acmeIdentifier id,")
|
||||
|
||||
ext := remoteCert.Extensions[idx]
|
||||
assert.True(t, ext.Critical, "Expected the challenge certificate id-pe-acmeIdentifier extension to be marked as critical")
|
||||
|
||||
zBytes := sha256.Sum256([]byte(chlng.KeyAuthorization))
|
||||
value, err := asn1.Marshal(zBytes[:sha256.Size])
|
||||
require.NoError(t, err, "Expected marshaling of the keyAuth to return no error")
|
||||
|
||||
if subtle.ConstantTimeCompare(value, ext.Value) != 1 {
|
||||
t.Errorf("Expected the challenge certificate id-pe-acmeIdentifier extension to contain the SHA-256 digest of the keyAuth, %v, but was %v", zBytes[:], ext.Value)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
solver := NewChallenge(
|
||||
core,
|
||||
mockValidate,
|
||||
&ProviderServer{port: "23457"},
|
||||
)
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Type: "dns",
|
||||
Value: domain,
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.TLSALPN01.String(), Token: "tlsalpn1"},
|
||||
},
|
||||
}
|
||||
|
||||
err = solver.Solve(authz)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestChallengeInvalidPort(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 128)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
solver := NewChallenge(
|
||||
core,
|
||||
func(_ *api.Core, _ string, _ acme.Challenge) error { return nil },
|
||||
&ProviderServer{port: "123456"},
|
||||
)
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Value: "localhost:123456",
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.TLSALPN01.String(), Token: "tlsalpn1"},
|
||||
},
|
||||
}
|
||||
|
||||
err = solver.Solve(authz)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "invalid port")
|
||||
assert.Contains(t, err.Error(), "123456")
|
||||
}
|
||||
|
||||
func TestChallengeIPaddress(t *testing.T) {
|
||||
_, apiURL := tester.SetupFakeAPI(t)
|
||||
|
||||
domain := "127.0.0.1"
|
||||
port := "23457"
|
||||
rd, _ := dns.ReverseAddr(domain)
|
||||
|
||||
mockValidate := func(_ *api.Core, _ string, chlng acme.Challenge) error {
|
||||
conn, err := tls.Dial("tcp", net.JoinHostPort(domain, port), &tls.Config{
|
||||
ServerName: rd,
|
||||
InsecureSkipVerify: true,
|
||||
})
|
||||
require.NoError(t, err, "Expected to connect to challenge server without an error")
|
||||
|
||||
// Expect the server to only return one certificate
|
||||
connState := conn.ConnectionState()
|
||||
assert.Len(t, connState.PeerCertificates, 1, "Expected the challenge server to return exactly one certificate")
|
||||
|
||||
remoteCert := connState.PeerCertificates[0]
|
||||
assert.Len(t, remoteCert.DNSNames, 0, "Expected the challenge certificate to have no DNSNames entry in context of challenge for IP")
|
||||
assert.Len(t, remoteCert.IPAddresses, 1, "Expected the challenge certificate to have exactly one IPAddresses entry")
|
||||
assert.True(t, net.ParseIP("127.0.0.1").Equal(remoteCert.IPAddresses[0]), "challenge certificate IPAddress ")
|
||||
assert.NotEmpty(t, remoteCert.Extensions, "Expected the challenge certificate to contain extensions")
|
||||
|
||||
var foundAcmeIdentifier bool
|
||||
var extValue []byte
|
||||
for _, ext := range remoteCert.Extensions {
|
||||
if idPeAcmeIdentifierV1.Equal(ext.Id) {
|
||||
assert.True(t, ext.Critical, "Expected the challenge certificate id-pe-acmeIdentifier extension to be marked as critical")
|
||||
foundAcmeIdentifier = true
|
||||
extValue = ext.Value
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
require.True(t, foundAcmeIdentifier, "Expected the challenge certificate to contain an extension with the id-pe-acmeIdentifier id,")
|
||||
zBytes := sha256.Sum256([]byte(chlng.KeyAuthorization))
|
||||
value, err := asn1.Marshal(zBytes[:sha256.Size])
|
||||
require.NoError(t, err, "Expected marshaling of the keyAuth to return no error")
|
||||
|
||||
require.EqualValues(t, value, extValue, "Expected the challenge certificate id-pe-acmeIdentifier extension to contain the SHA-256 digest of the keyAuth")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 512)
|
||||
require.NoError(t, err, "Could not generate test key")
|
||||
|
||||
core, err := api.New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
solver := NewChallenge(
|
||||
core,
|
||||
mockValidate,
|
||||
&ProviderServer{port: "23457"},
|
||||
)
|
||||
|
||||
authz := acme.Authorization{
|
||||
Identifier: acme.Identifier{
|
||||
Type: "ip",
|
||||
Value: domain,
|
||||
},
|
||||
Challenges: []acme.Challenge{
|
||||
{Type: challenge.TLSALPN01.String(), Token: "tlsalpn1"},
|
||||
},
|
||||
}
|
||||
|
||||
require.NoError(t, solver.Solve(authz))
|
||||
}
|
31
cmd/account.go
Normal file
31
cmd/account.go
Normal file
|
@ -0,0 +1,31 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
)
|
||||
|
||||
// Account represents a users local saved credentials.
|
||||
type Account struct {
|
||||
Email string `json:"email"`
|
||||
Registration *registration.Resource `json:"registration"`
|
||||
key crypto.PrivateKey
|
||||
}
|
||||
|
||||
/** Implementation of the registration.User interface **/
|
||||
|
||||
// GetEmail returns the email address for the account.
|
||||
func (a *Account) GetEmail() string {
|
||||
return a.Email
|
||||
}
|
||||
|
||||
// GetPrivateKey returns the private RSA account key.
|
||||
func (a *Account) GetPrivateKey() crypto.PrivateKey {
|
||||
return a.key
|
||||
}
|
||||
|
||||
// GetRegistration returns the server registration.
|
||||
func (a *Account) GetRegistration() *registration.Resource {
|
||||
return a.Registration
|
||||
}
|
240
cmd/accounts_storage.go
Normal file
240
cmd/accounts_storage.go
Normal file
|
@ -0,0 +1,240 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
const (
|
||||
baseAccountsRootFolderName = "accounts"
|
||||
baseKeysFolderName = "keys"
|
||||
accountFileName = "account.json"
|
||||
)
|
||||
|
||||
// AccountsStorage A storage for account data.
|
||||
//
|
||||
// rootPath:
|
||||
//
|
||||
// ./.lego/accounts/
|
||||
// │ └── root accounts directory
|
||||
// └── "path" option
|
||||
//
|
||||
// rootUserPath:
|
||||
//
|
||||
// ./.lego/accounts/localhost_14000/hubert@hubert.com/
|
||||
// │ │ │ └── userID ("email" option)
|
||||
// │ │ └── CA server ("server" option)
|
||||
// │ └── root accounts directory
|
||||
// └── "path" option
|
||||
//
|
||||
// keysPath:
|
||||
//
|
||||
// ./.lego/accounts/localhost_14000/hubert@hubert.com/keys/
|
||||
// │ │ │ │ └── root keys directory
|
||||
// │ │ │ └── userID ("email" option)
|
||||
// │ │ └── CA server ("server" option)
|
||||
// │ └── root accounts directory
|
||||
// └── "path" option
|
||||
//
|
||||
// accountFilePath:
|
||||
//
|
||||
// ./.lego/accounts/localhost_14000/hubert@hubert.com/account.json
|
||||
// │ │ │ │ └── account file
|
||||
// │ │ │ └── userID ("email" option)
|
||||
// │ │ └── CA server ("server" option)
|
||||
// │ └── root accounts directory
|
||||
// └── "path" option
|
||||
type AccountsStorage struct {
|
||||
userID string
|
||||
rootPath string
|
||||
rootUserPath string
|
||||
keysPath string
|
||||
accountFilePath string
|
||||
ctx *cli.Context
|
||||
}
|
||||
|
||||
// NewAccountsStorage Creates a new AccountsStorage.
|
||||
func NewAccountsStorage(ctx *cli.Context) *AccountsStorage {
|
||||
// TODO: move to account struct? Currently MUST pass email.
|
||||
email := getEmail(ctx)
|
||||
|
||||
serverURL, err := url.Parse(ctx.String("server"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
rootPath := filepath.Join(ctx.String("path"), baseAccountsRootFolderName)
|
||||
serverPath := strings.NewReplacer(":", "_", "/", string(os.PathSeparator)).Replace(serverURL.Host)
|
||||
accountsPath := filepath.Join(rootPath, serverPath)
|
||||
rootUserPath := filepath.Join(accountsPath, email)
|
||||
|
||||
return &AccountsStorage{
|
||||
userID: email,
|
||||
rootPath: rootPath,
|
||||
rootUserPath: rootUserPath,
|
||||
keysPath: filepath.Join(rootUserPath, baseKeysFolderName),
|
||||
accountFilePath: filepath.Join(rootUserPath, accountFileName),
|
||||
ctx: ctx,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) ExistsAccountFilePath() bool {
|
||||
accountFile := filepath.Join(s.rootUserPath, accountFileName)
|
||||
if _, err := os.Stat(accountFile); os.IsNotExist(err) {
|
||||
return false
|
||||
} else if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) GetRootPath() string {
|
||||
return s.rootPath
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) GetRootUserPath() string {
|
||||
return s.rootUserPath
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) GetUserID() string {
|
||||
return s.userID
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) Save(account *Account) error {
|
||||
jsonBytes, err := json.MarshalIndent(account, "", "\t")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(s.accountFilePath, jsonBytes, filePerm)
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) LoadAccount(privateKey crypto.PrivateKey) *Account {
|
||||
fileBytes, err := os.ReadFile(s.accountFilePath)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not load file for account %s: %v", s.userID, err)
|
||||
}
|
||||
|
||||
var account Account
|
||||
err = json.Unmarshal(fileBytes, &account)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not parse file for account %s: %v", s.userID, err)
|
||||
}
|
||||
|
||||
account.key = privateKey
|
||||
|
||||
if account.Registration == nil || account.Registration.Body.Status == "" {
|
||||
reg, err := tryRecoverRegistration(s.ctx, privateKey)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not load account for %s. Registration is nil: %#v", s.userID, err)
|
||||
}
|
||||
|
||||
account.Registration = reg
|
||||
err = s.Save(&account)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not save account for %s. Registration is nil: %#v", s.userID, err)
|
||||
}
|
||||
}
|
||||
|
||||
return &account
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) GetPrivateKey(keyType certcrypto.KeyType) crypto.PrivateKey {
|
||||
accKeyPath := filepath.Join(s.keysPath, s.userID+".key")
|
||||
|
||||
if _, err := os.Stat(accKeyPath); os.IsNotExist(err) {
|
||||
log.Printf("No key found for account %s. Generating a %s key.", s.userID, keyType)
|
||||
s.createKeysFolder()
|
||||
|
||||
privateKey, err := generatePrivateKey(accKeyPath, keyType)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not generate RSA private account key for account %s: %v", s.userID, err)
|
||||
}
|
||||
|
||||
log.Printf("Saved key to %s", accKeyPath)
|
||||
return privateKey
|
||||
}
|
||||
|
||||
privateKey, err := loadPrivateKey(accKeyPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not load RSA private key from file %s: %v", accKeyPath, err)
|
||||
}
|
||||
|
||||
return privateKey
|
||||
}
|
||||
|
||||
func (s *AccountsStorage) createKeysFolder() {
|
||||
if err := createNonExistingFolder(s.keysPath); err != nil {
|
||||
log.Fatalf("Could not check/create directory for account %s: %v", s.userID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func generatePrivateKey(file string, keyType certcrypto.KeyType) (crypto.PrivateKey, error) {
|
||||
privateKey, err := certcrypto.GeneratePrivateKey(keyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
certOut, err := os.Create(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer certOut.Close()
|
||||
|
||||
pemKey := certcrypto.PEMBlock(privateKey)
|
||||
err = pem.Encode(certOut, pemKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return privateKey, nil
|
||||
}
|
||||
|
||||
func loadPrivateKey(file string) (crypto.PrivateKey, error) {
|
||||
keyBytes, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keyBlock, _ := pem.Decode(keyBytes)
|
||||
|
||||
switch keyBlock.Type {
|
||||
case "RSA PRIVATE KEY":
|
||||
return x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
|
||||
case "EC PRIVATE KEY":
|
||||
return x509.ParseECPrivateKey(keyBlock.Bytes)
|
||||
}
|
||||
|
||||
return nil, errors.New("unknown private key type")
|
||||
}
|
||||
|
||||
func tryRecoverRegistration(ctx *cli.Context, privateKey crypto.PrivateKey) (*registration.Resource, error) {
|
||||
// couldn't load account but got a key. Try to look the account up.
|
||||
config := lego.NewConfig(&Account{key: privateKey})
|
||||
config.CADirURL = ctx.String("server")
|
||||
config.UserAgent = getUserAgent(ctx)
|
||||
|
||||
client, err := lego.NewClient(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reg, err := client.Registration.ResolveAccountByKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reg, nil
|
||||
}
|
295
cmd/certs_storage.go
Normal file
295
cmd/certs_storage.go
Normal file
|
@ -0,0 +1,295 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/certificate"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/net/idna"
|
||||
"software.sslmate.com/src/go-pkcs12"
|
||||
)
|
||||
|
||||
const (
|
||||
baseCertificatesFolderName = "certificates"
|
||||
baseArchivesFolderName = "archives"
|
||||
)
|
||||
|
||||
const (
|
||||
issuerExt = ".issuer.crt"
|
||||
certExt = ".crt"
|
||||
keyExt = ".key"
|
||||
pemExt = ".pem"
|
||||
pfxExt = ".pfx"
|
||||
resourceExt = ".json"
|
||||
)
|
||||
|
||||
// CertificatesStorage a certificates' storage.
|
||||
//
|
||||
// rootPath:
|
||||
//
|
||||
// ./.lego/certificates/
|
||||
// │ └── root certificates directory
|
||||
// └── "path" option
|
||||
//
|
||||
// archivePath:
|
||||
//
|
||||
// ./.lego/archives/
|
||||
// │ └── archived certificates directory
|
||||
// └── "path" option
|
||||
type CertificatesStorage struct {
|
||||
rootPath string
|
||||
archivePath string
|
||||
pem bool
|
||||
pfx bool
|
||||
pfxPassword string
|
||||
filename string // Deprecated
|
||||
}
|
||||
|
||||
// NewCertificatesStorage create a new certificates storage.
|
||||
func NewCertificatesStorage(ctx *cli.Context) *CertificatesStorage {
|
||||
return &CertificatesStorage{
|
||||
rootPath: filepath.Join(ctx.String("path"), baseCertificatesFolderName),
|
||||
archivePath: filepath.Join(ctx.String("path"), baseArchivesFolderName),
|
||||
pem: ctx.Bool("pem"),
|
||||
pfx: ctx.Bool("pfx"),
|
||||
pfxPassword: ctx.String("pfx.pass"),
|
||||
filename: ctx.String("filename"),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) CreateRootFolder() {
|
||||
err := createNonExistingFolder(s.rootPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not check/create path: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) CreateArchiveFolder() {
|
||||
err := createNonExistingFolder(s.archivePath)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not check/create path: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) GetRootPath() string {
|
||||
return s.rootPath
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) SaveResource(certRes *certificate.Resource) {
|
||||
domain := certRes.Domain
|
||||
|
||||
// We store the certificate, private key and metadata in different files
|
||||
// as web servers would not be able to work with a combined file.
|
||||
err := s.WriteFile(domain, certExt, certRes.Certificate)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to save Certificate for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
if certRes.IssuerCertificate != nil {
|
||||
err = s.WriteFile(domain, issuerExt, certRes.IssuerCertificate)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to save IssuerCertificate for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
}
|
||||
|
||||
// if we were given a CSR, we don't know the private key
|
||||
if certRes.PrivateKey != nil {
|
||||
err = s.WriteCertificateFiles(domain, certRes)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to save PrivateKey for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
} else if s.pem || s.pfx {
|
||||
// we don't have the private key; can't write the .pem or .pfx file
|
||||
log.Fatalf("Unable to save PEM or PFX without private key for domain %s. Are you using a CSR?", domain)
|
||||
}
|
||||
|
||||
jsonBytes, err := json.MarshalIndent(certRes, "", "\t")
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to marshal CertResource for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
err = s.WriteFile(domain, resourceExt, jsonBytes)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to save CertResource for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) ReadResource(domain string) certificate.Resource {
|
||||
raw, err := s.ReadFile(domain, resourceExt)
|
||||
if err != nil {
|
||||
log.Fatalf("Error while loading the meta data for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
var resource certificate.Resource
|
||||
if err = json.Unmarshal(raw, &resource); err != nil {
|
||||
log.Fatalf("Error while marshaling the meta data for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
return resource
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) ExistsFile(domain, extension string) bool {
|
||||
filePath := s.GetFileName(domain, extension)
|
||||
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
return false
|
||||
} else if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) ReadFile(domain, extension string) ([]byte, error) {
|
||||
return os.ReadFile(s.GetFileName(domain, extension))
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) GetFileName(domain, extension string) string {
|
||||
filename := sanitizedDomain(domain) + extension
|
||||
return filepath.Join(s.rootPath, filename)
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) ReadCertificate(domain, extension string) ([]*x509.Certificate, error) {
|
||||
content, err := s.ReadFile(domain, extension)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The input may be a bundle or a single certificate.
|
||||
return certcrypto.ParsePEMBundle(content)
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) WriteFile(domain, extension string, data []byte) error {
|
||||
var baseFileName string
|
||||
if s.filename != "" {
|
||||
baseFileName = s.filename
|
||||
} else {
|
||||
baseFileName = sanitizedDomain(domain)
|
||||
}
|
||||
|
||||
filePath := filepath.Join(s.rootPath, baseFileName+extension)
|
||||
|
||||
return os.WriteFile(filePath, data, filePerm)
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) WriteCertificateFiles(domain string, certRes *certificate.Resource) error {
|
||||
err := s.WriteFile(domain, keyExt, certRes.PrivateKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to save key file: %w", err)
|
||||
}
|
||||
|
||||
if s.pem {
|
||||
err = s.WriteFile(domain, pemExt, bytes.Join([][]byte{certRes.Certificate, certRes.PrivateKey}, nil))
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to save PEM file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if s.pfx {
|
||||
err = s.WritePFXFile(domain, certRes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to save PFX file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) WritePFXFile(domain string, certRes *certificate.Resource) error {
|
||||
certPemBlock, _ := pem.Decode(certRes.Certificate)
|
||||
if certPemBlock == nil {
|
||||
return fmt.Errorf("unable to parse Certificate for domain %s", domain)
|
||||
}
|
||||
|
||||
cert, err := x509.ParseCertificate(certPemBlock.Bytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to load Certificate for domain %s: %w", domain, err)
|
||||
}
|
||||
|
||||
issuerCertPemBlock, _ := pem.Decode(certRes.IssuerCertificate)
|
||||
if issuerCertPemBlock == nil {
|
||||
return fmt.Errorf("unable to parse Issuer Certificate for domain %s", domain)
|
||||
}
|
||||
|
||||
issuerCert, err := x509.ParseCertificate(issuerCertPemBlock.Bytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to load Issuer Certificate for domain %s: %w", domain, err)
|
||||
}
|
||||
|
||||
keyPemBlock, _ := pem.Decode(certRes.PrivateKey)
|
||||
if keyPemBlock == nil {
|
||||
return fmt.Errorf("unable to parse PrivateKey for domain %s", domain)
|
||||
}
|
||||
|
||||
var privateKey crypto.Signer
|
||||
var keyErr error
|
||||
|
||||
switch keyPemBlock.Type {
|
||||
case "RSA PRIVATE KEY":
|
||||
privateKey, keyErr = x509.ParsePKCS1PrivateKey(keyPemBlock.Bytes)
|
||||
if keyErr != nil {
|
||||
return fmt.Errorf("unable to load RSA PrivateKey for domain %s: %w", domain, keyErr)
|
||||
}
|
||||
case "EC PRIVATE KEY":
|
||||
privateKey, keyErr = x509.ParseECPrivateKey(keyPemBlock.Bytes)
|
||||
if keyErr != nil {
|
||||
return fmt.Errorf("unable to load EC PrivateKey for domain %s: %w", domain, keyErr)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unsupported PrivateKey type '%s' for domain %s", keyPemBlock.Type, domain)
|
||||
}
|
||||
|
||||
pfxBytes, err := pkcs12.Encode(rand.Reader, privateKey, cert, []*x509.Certificate{issuerCert}, s.pfxPassword)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to encode PFX data for domain %s: %w", domain, err)
|
||||
}
|
||||
|
||||
return s.WriteFile(domain, pfxExt, pfxBytes)
|
||||
}
|
||||
|
||||
func (s *CertificatesStorage) MoveToArchive(domain string) error {
|
||||
baseFilename := filepath.Join(s.rootPath, sanitizedDomain(domain))
|
||||
|
||||
matches, err := filepath.Glob(baseFilename + ".*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, oldFile := range matches {
|
||||
if strings.TrimSuffix(oldFile, filepath.Ext(oldFile)) != baseFilename && oldFile != baseFilename+issuerExt {
|
||||
continue
|
||||
}
|
||||
|
||||
date := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
filename := date + "." + filepath.Base(oldFile)
|
||||
newFile := filepath.Join(s.archivePath, filename)
|
||||
|
||||
err = os.Rename(oldFile, newFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// sanitizedDomain Make sure no funny chars are in the cert names (like wildcards ;)).
|
||||
func sanitizedDomain(domain string) string {
|
||||
safe, err := idna.ToASCII(strings.NewReplacer(":", "-", "*", "_").Replace(domain))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return safe
|
||||
}
|
115
cmd/certs_storage_test.go
Normal file
115
cmd/certs_storage_test.go
Normal file
|
@ -0,0 +1,115 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCertificatesStorage_MoveToArchive(t *testing.T) {
|
||||
domain := "example.com"
|
||||
|
||||
storage := CertificatesStorage{
|
||||
rootPath: t.TempDir(),
|
||||
archivePath: t.TempDir(),
|
||||
}
|
||||
|
||||
domainFiles := generateTestFiles(t, storage.rootPath, domain)
|
||||
|
||||
err := storage.MoveToArchive(domain)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, file := range domainFiles {
|
||||
assert.NoFileExists(t, file)
|
||||
}
|
||||
|
||||
root, err := os.ReadDir(storage.rootPath)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, root)
|
||||
|
||||
archive, err := os.ReadDir(storage.archivePath)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, archive, len(domainFiles))
|
||||
assert.Regexp(t, `\d+\.`+regexp.QuoteMeta(domain), archive[0].Name())
|
||||
}
|
||||
|
||||
func TestCertificatesStorage_MoveToArchive_noFileRelatedToDomain(t *testing.T) {
|
||||
domain := "example.com"
|
||||
|
||||
storage := CertificatesStorage{
|
||||
rootPath: t.TempDir(),
|
||||
archivePath: t.TempDir(),
|
||||
}
|
||||
|
||||
domainFiles := generateTestFiles(t, storage.rootPath, "example.org")
|
||||
|
||||
err := storage.MoveToArchive(domain)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, file := range domainFiles {
|
||||
assert.FileExists(t, file)
|
||||
}
|
||||
|
||||
root, err := os.ReadDir(storage.rootPath)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, root, len(domainFiles))
|
||||
|
||||
archive, err := os.ReadDir(storage.archivePath)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Empty(t, archive)
|
||||
}
|
||||
|
||||
func TestCertificatesStorage_MoveToArchive_ambiguousDomain(t *testing.T) {
|
||||
domain := "example.com"
|
||||
|
||||
storage := CertificatesStorage{
|
||||
rootPath: t.TempDir(),
|
||||
archivePath: t.TempDir(),
|
||||
}
|
||||
|
||||
domainFiles := generateTestFiles(t, storage.rootPath, domain)
|
||||
otherDomainFiles := generateTestFiles(t, storage.rootPath, domain+".example.org")
|
||||
|
||||
err := storage.MoveToArchive(domain)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, file := range domainFiles {
|
||||
assert.NoFileExists(t, file)
|
||||
}
|
||||
|
||||
for _, file := range otherDomainFiles {
|
||||
assert.FileExists(t, file)
|
||||
}
|
||||
|
||||
root, err := os.ReadDir(storage.rootPath)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, root, len(otherDomainFiles))
|
||||
|
||||
archive, err := os.ReadDir(storage.archivePath)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, archive, len(domainFiles))
|
||||
assert.Regexp(t, `\d+\.`+regexp.QuoteMeta(domain), archive[0].Name())
|
||||
}
|
||||
|
||||
func generateTestFiles(t *testing.T, dir, domain string) []string {
|
||||
t.Helper()
|
||||
|
||||
var filenames []string
|
||||
|
||||
for _, ext := range []string{issuerExt, certExt, keyExt, pemExt, pfxExt, resourceExt} {
|
||||
filename := filepath.Join(dir, domain+ext)
|
||||
err := os.WriteFile(filename, []byte("test"), 0o666)
|
||||
require.NoError(t, err)
|
||||
|
||||
filenames = append(filenames, filename)
|
||||
}
|
||||
|
||||
return filenames
|
||||
}
|
14
cmd/cmd.go
Normal file
14
cmd/cmd.go
Normal file
|
@ -0,0 +1,14 @@
|
|||
package cmd
|
||||
|
||||
import "github.com/urfave/cli/v2"
|
||||
|
||||
// CreateCommands Creates all CLI commands.
|
||||
func CreateCommands() []*cli.Command {
|
||||
return []*cli.Command{
|
||||
createRun(),
|
||||
createRevoke(),
|
||||
createRenew(),
|
||||
createDNSHelp(),
|
||||
createList(),
|
||||
}
|
||||
}
|
23
cmd/cmd_before.go
Normal file
23
cmd/cmd_before.go
Normal file
|
@ -0,0 +1,23 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func Before(ctx *cli.Context) error {
|
||||
if ctx.String("path") == "" {
|
||||
log.Fatal("Could not determine current working directory. Please pass --path.")
|
||||
}
|
||||
|
||||
err := createNonExistingFolder(ctx.String("path"))
|
||||
if err != nil {
|
||||
log.Fatalf("Could not check/create path: %v", err)
|
||||
}
|
||||
|
||||
if ctx.String("server") == "" {
|
||||
log.Fatal("Could not determine current working server. Please pass --server.")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
73
cmd/cmd_dnshelp.go
Normal file
73
cmd/cmd_dnshelp.go
Normal file
|
@ -0,0 +1,73 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func createDNSHelp() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "dnshelp",
|
||||
Usage: "Shows additional help for the '--dns' global option",
|
||||
Action: dnsHelp,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "code",
|
||||
Aliases: []string{"c"},
|
||||
Usage: fmt.Sprintf("DNS code: %s", allDNSCodes()),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func dnsHelp(ctx *cli.Context) error {
|
||||
code := ctx.String("code")
|
||||
if code == "" {
|
||||
w := tabwriter.NewWriter(ctx.App.Writer, 0, 0, 2, ' ', 0)
|
||||
ew := &errWriter{w: w}
|
||||
|
||||
ew.writeln(`Credentials for DNS providers must be passed through environment variables.`)
|
||||
ew.writeln()
|
||||
ew.writeln(`To display the documentation for a specific DNS provider, run:`)
|
||||
ew.writeln()
|
||||
ew.writeln("\t$ lego dnshelp -c code")
|
||||
ew.writeln()
|
||||
ew.writeln("Supported DNS providers:")
|
||||
ew.writef("\t%s\n", allDNSCodes())
|
||||
ew.writeln()
|
||||
ew.writeln("More information: https://go-acme.github.io/lego/dns")
|
||||
|
||||
if ew.err != nil {
|
||||
return ew.err
|
||||
}
|
||||
|
||||
return w.Flush()
|
||||
}
|
||||
|
||||
return displayDNSHelp(ctx.App.Writer, strings.ToLower(code))
|
||||
}
|
||||
|
||||
type errWriter struct {
|
||||
w io.Writer
|
||||
err error
|
||||
}
|
||||
|
||||
func (ew *errWriter) writeln(a ...interface{}) {
|
||||
if ew.err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, ew.err = fmt.Fprintln(ew.w, a...)
|
||||
}
|
||||
|
||||
func (ew *errWriter) writef(format string, a ...interface{}) {
|
||||
if ew.err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, ew.err = fmt.Fprintf(ew.w, format, a...)
|
||||
}
|
139
cmd/cmd_list.go
Normal file
139
cmd/cmd_list.go
Normal file
|
@ -0,0 +1,139 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func createList() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "list",
|
||||
Usage: "Display certificates and accounts information.",
|
||||
Action: list,
|
||||
Flags: []cli.Flag{
|
||||
&cli.BoolFlag{
|
||||
Name: "accounts",
|
||||
Aliases: []string{"a"},
|
||||
Usage: "Display accounts.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "names",
|
||||
Aliases: []string{"n"},
|
||||
Usage: "Display certificate common names only.",
|
||||
},
|
||||
// fake email, needed by NewAccountsStorage
|
||||
&cli.StringFlag{
|
||||
Name: "email",
|
||||
Value: "unknown",
|
||||
Hidden: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func list(ctx *cli.Context) error {
|
||||
if ctx.Bool("accounts") && !ctx.Bool("names") {
|
||||
if err := listAccount(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return listCertificates(ctx)
|
||||
}
|
||||
|
||||
func listCertificates(ctx *cli.Context) error {
|
||||
certsStorage := NewCertificatesStorage(ctx)
|
||||
|
||||
matches, err := filepath.Glob(filepath.Join(certsStorage.GetRootPath(), "*.crt"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
names := ctx.Bool("names")
|
||||
|
||||
if len(matches) == 0 {
|
||||
if !names {
|
||||
fmt.Println("No certificates found.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if !names {
|
||||
fmt.Println("Found the following certs:")
|
||||
}
|
||||
|
||||
for _, filename := range matches {
|
||||
if strings.HasSuffix(filename, ".issuer.crt") {
|
||||
continue
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pCert, err := certcrypto.ParsePEMCertificate(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if names {
|
||||
fmt.Println(pCert.Subject.CommonName)
|
||||
} else {
|
||||
fmt.Println(" Certificate Name:", pCert.Subject.CommonName)
|
||||
fmt.Println(" Domains:", strings.Join(pCert.DNSNames, ", "))
|
||||
fmt.Println(" Expiry Date:", pCert.NotAfter)
|
||||
fmt.Println(" Certificate Path:", filename)
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func listAccount(ctx *cli.Context) error {
|
||||
accountsStorage := NewAccountsStorage(ctx)
|
||||
|
||||
matches, err := filepath.Glob(filepath.Join(accountsStorage.GetRootPath(), "*", "*", "*.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(matches) == 0 {
|
||||
fmt.Println("No accounts found.")
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Println("Found the following accounts:")
|
||||
for _, filename := range matches {
|
||||
data, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var account Account
|
||||
err = json.Unmarshal(data, &account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
uri, err := url.Parse(account.Registration.URI)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println(" Email:", account.Email)
|
||||
fmt.Println(" Server:", uri.Host)
|
||||
fmt.Println(" Path:", filepath.Dir(filename))
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
383
cmd/cmd_renew.go
Normal file
383
cmd/cmd_renew.go
Normal file
|
@ -0,0 +1,383 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"math/rand"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/acme/api"
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
"github.com/go-acme/lego/v4/certificate"
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
const (
|
||||
renewEnvAccountEmail = "LEGO_ACCOUNT_EMAIL"
|
||||
renewEnvCertDomain = "LEGO_CERT_DOMAIN"
|
||||
renewEnvCertPath = "LEGO_CERT_PATH"
|
||||
renewEnvCertKeyPath = "LEGO_CERT_KEY_PATH"
|
||||
renewEnvCertPEMPath = "LEGO_CERT_PEM_PATH"
|
||||
renewEnvCertPFXPath = "LEGO_CERT_PFX_PATH"
|
||||
)
|
||||
|
||||
func createRenew() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "renew",
|
||||
Usage: "Renew a certificate",
|
||||
Action: renew,
|
||||
Before: func(ctx *cli.Context) error {
|
||||
// we require either domains or csr, but not both
|
||||
hasDomains := len(ctx.StringSlice("domains")) > 0
|
||||
hasCsr := len(ctx.String("csr")) > 0
|
||||
if hasDomains && hasCsr {
|
||||
log.Fatal("Please specify either --domains/-d or --csr/-c, but not both")
|
||||
}
|
||||
if !hasDomains && !hasCsr {
|
||||
log.Fatal("Please specify --domains/-d (or --csr/-c if you already have a CSR)")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
&cli.IntFlag{
|
||||
Name: "days",
|
||||
Value: 30,
|
||||
Usage: "The number of days left on a certificate to renew it.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "ari-enable",
|
||||
Usage: "Use the renewalInfo endpoint (draft-ietf-acme-ari) to check if a certificate should be renewed.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "ari-hash-name",
|
||||
Value: crypto.SHA256.String(),
|
||||
Usage: "The string representation of the hash expected by the renewalInfo endpoint (e.g. \"SHA-256\").",
|
||||
},
|
||||
&cli.DurationFlag{
|
||||
Name: "ari-wait-to-renew-duration",
|
||||
Usage: "The maximum duration you're willing to sleep for a renewal time returned by the renewalInfo endpoint.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "reuse-key",
|
||||
Usage: "Used to indicate you want to reuse your current private key for the new certificate.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "no-bundle",
|
||||
Usage: "Do not create a certificate bundle by adding the issuers certificate to the new certificate.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "must-staple",
|
||||
Usage: "Include the OCSP must staple TLS extension in the CSR and generated certificate." +
|
||||
" Only works if the CSR is generated by lego.",
|
||||
},
|
||||
&cli.TimestampFlag{
|
||||
Name: "not-before",
|
||||
Usage: "Set the notBefore field in the certificate (RFC3339 format)",
|
||||
Layout: time.RFC3339,
|
||||
},
|
||||
&cli.TimestampFlag{
|
||||
Name: "not-after",
|
||||
Usage: "Set the notAfter field in the certificate (RFC3339 format)",
|
||||
Layout: time.RFC3339,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "preferred-chain",
|
||||
Usage: "If the CA offers multiple certificate chains, prefer the chain with an issuer matching this Subject Common Name." +
|
||||
" If no match, the default offered chain will be used.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "always-deactivate-authorizations",
|
||||
Usage: "Force the authorizations to be relinquished even if the certificate request was successful.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "renew-hook",
|
||||
Usage: "Define a hook. The hook is executed only when the certificates are effectively renewed.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "no-random-sleep",
|
||||
Usage: "Do not add a random sleep before the renewal." +
|
||||
" We do not recommend using this flag if you are doing your renewals in an automated way.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func renew(ctx *cli.Context) error {
|
||||
account, client := setup(ctx, NewAccountsStorage(ctx))
|
||||
setupChallenges(ctx, client)
|
||||
|
||||
if account.Registration == nil {
|
||||
log.Fatalf("Account %s is not registered. Use 'run' to register a new account.\n", account.Email)
|
||||
}
|
||||
|
||||
certsStorage := NewCertificatesStorage(ctx)
|
||||
|
||||
bundle := !ctx.Bool("no-bundle")
|
||||
|
||||
meta := map[string]string{renewEnvAccountEmail: account.Email}
|
||||
|
||||
// CSR
|
||||
if ctx.IsSet("csr") {
|
||||
return renewForCSR(ctx, client, certsStorage, bundle, meta)
|
||||
}
|
||||
|
||||
// Domains
|
||||
return renewForDomains(ctx, client, certsStorage, bundle, meta)
|
||||
}
|
||||
|
||||
func renewForDomains(ctx *cli.Context, client *lego.Client, certsStorage *CertificatesStorage, bundle bool, meta map[string]string) error {
|
||||
domains := ctx.StringSlice("domains")
|
||||
domain := domains[0]
|
||||
|
||||
// load the cert resource from files.
|
||||
// We store the certificate, private key and metadata in different files
|
||||
// as web servers would not be able to work with a combined file.
|
||||
certificates, err := certsStorage.ReadCertificate(domain, ".crt")
|
||||
if err != nil {
|
||||
log.Fatalf("Error while loading the certificate for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
cert := certificates[0]
|
||||
|
||||
var ariRenewalTime *time.Time
|
||||
if ctx.Bool("ari-enable") {
|
||||
if len(certificates) < 2 {
|
||||
log.Warnf("[%s] Certificate bundle does not contain issuer, cannot use the renewalInfo endpoint", domain)
|
||||
} else {
|
||||
ariRenewalTime = getARIRenewalTime(ctx, certificates[0], certificates[1], domain, client)
|
||||
}
|
||||
if ariRenewalTime != nil {
|
||||
now := time.Now().UTC()
|
||||
// Figure out if we need to sleep before renewing.
|
||||
if ariRenewalTime.After(now) {
|
||||
log.Infof("[%s] Sleeping %s until renewal time %s", domain, ariRenewalTime.Sub(now), ariRenewalTime)
|
||||
time.Sleep(ariRenewalTime.Sub(now))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ariRenewalTime == nil && !needRenewal(cert, domain, ctx.Int("days")) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// This is just meant to be informal for the user.
|
||||
timeLeft := cert.NotAfter.Sub(time.Now().UTC())
|
||||
log.Infof("[%s] acme: Trying renewal with %d hours remaining", domain, int(timeLeft.Hours()))
|
||||
|
||||
certDomains := certcrypto.ExtractDomains(cert)
|
||||
|
||||
var privateKey crypto.PrivateKey
|
||||
if ctx.Bool("reuse-key") {
|
||||
keyBytes, errR := certsStorage.ReadFile(domain, ".key")
|
||||
if errR != nil {
|
||||
log.Fatalf("Error while loading the private key for domain %s\n\t%v", domain, errR)
|
||||
}
|
||||
|
||||
privateKey, errR = certcrypto.ParsePEMPrivateKey(keyBytes)
|
||||
if errR != nil {
|
||||
return errR
|
||||
}
|
||||
}
|
||||
|
||||
// https://github.com/go-acme/lego/issues/1656
|
||||
// https://github.com/certbot/certbot/blob/284023a1b7672be2bd4018dd7623b3b92197d4b0/certbot/certbot/_internal/renewal.py#L435-L440
|
||||
if !isatty.IsTerminal(os.Stdout.Fd()) && !ctx.Bool("no-random-sleep") {
|
||||
// https://github.com/certbot/certbot/blob/284023a1b7672be2bd4018dd7623b3b92197d4b0/certbot/certbot/_internal/renewal.py#L472
|
||||
const jitter = 8 * time.Minute
|
||||
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
sleepTime := time.Duration(rnd.Int63n(int64(jitter)))
|
||||
|
||||
log.Infof("renewal: random delay of %s", sleepTime)
|
||||
time.Sleep(sleepTime)
|
||||
}
|
||||
|
||||
request := certificate.ObtainRequest{
|
||||
Domains: merge(certDomains, domains),
|
||||
PrivateKey: privateKey,
|
||||
MustStaple: ctx.Bool("must-staple"),
|
||||
NotBefore: getTime(ctx, "not-before"),
|
||||
NotAfter: getTime(ctx, "not-after"),
|
||||
Bundle: bundle,
|
||||
PreferredChain: ctx.String("preferred-chain"),
|
||||
AlwaysDeactivateAuthorizations: ctx.Bool("always-deactivate-authorizations"),
|
||||
}
|
||||
|
||||
certRes, err := client.Certificate.Obtain(request)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
certsStorage.SaveResource(certRes)
|
||||
|
||||
if ariRenewalTime != nil {
|
||||
// Post to the renewalInfo endpoint to indicate that we have renewed and replaced the certificate.
|
||||
err := client.Certificate.UpdateRenewalInfo(certificate.RenewalInfoRequest{
|
||||
Cert: certificates[0],
|
||||
Issuer: certificates[1],
|
||||
HashName: ctx.String("ari-hash-name"),
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("[%s] Failed to update renewal info: %v", domain, err)
|
||||
}
|
||||
}
|
||||
|
||||
meta[renewEnvCertDomain] = domain
|
||||
meta[renewEnvCertPath] = certsStorage.GetFileName(domain, ".crt")
|
||||
meta[renewEnvCertKeyPath] = certsStorage.GetFileName(domain, ".key")
|
||||
meta[renewEnvCertPEMPath] = certsStorage.GetFileName(domain, ".pem")
|
||||
meta[renewEnvCertPFXPath] = certsStorage.GetFileName(domain, ".pfx")
|
||||
|
||||
return launchHook(ctx.String("renew-hook"), meta)
|
||||
}
|
||||
|
||||
func renewForCSR(ctx *cli.Context, client *lego.Client, certsStorage *CertificatesStorage, bundle bool, meta map[string]string) error {
|
||||
csr, err := readCSRFile(ctx.String("csr"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
domain := csr.Subject.CommonName
|
||||
|
||||
// load the cert resource from files.
|
||||
// We store the certificate, private key and metadata in different files
|
||||
// as web servers would not be able to work with a combined file.
|
||||
certificates, err := certsStorage.ReadCertificate(domain, ".crt")
|
||||
if err != nil {
|
||||
log.Fatalf("Error while loading the certificate for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
cert := certificates[0]
|
||||
|
||||
var ariRenewalTime *time.Time
|
||||
if ctx.Bool("ari-enable") {
|
||||
if len(certificates) < 2 {
|
||||
log.Warnf("[%s] Certificate bundle does not contain issuer, cannot use the renewalInfo endpoint", domain)
|
||||
} else {
|
||||
ariRenewalTime = getARIRenewalTime(ctx, certificates[0], certificates[1], domain, client)
|
||||
}
|
||||
if ariRenewalTime != nil {
|
||||
now := time.Now().UTC()
|
||||
// Figure out if we need to sleep before renewing.
|
||||
if ariRenewalTime.After(now) {
|
||||
log.Infof("[%s] Sleeping %s until renewal time %s", domain, ariRenewalTime.Sub(now), ariRenewalTime)
|
||||
time.Sleep(ariRenewalTime.Sub(now))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ariRenewalTime == nil && !needRenewal(cert, domain, ctx.Int("days")) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// This is just meant to be informal for the user.
|
||||
timeLeft := cert.NotAfter.Sub(time.Now().UTC())
|
||||
log.Infof("[%s] acme: Trying renewal with %d hours remaining", domain, int(timeLeft.Hours()))
|
||||
|
||||
request := certificate.ObtainForCSRRequest{
|
||||
CSR: csr,
|
||||
NotBefore: getTime(ctx, "not-before"),
|
||||
NotAfter: getTime(ctx, "not-after"),
|
||||
Bundle: bundle,
|
||||
PreferredChain: ctx.String("preferred-chain"),
|
||||
AlwaysDeactivateAuthorizations: ctx.Bool("always-deactivate-authorizations"),
|
||||
}
|
||||
|
||||
certRes, err := client.Certificate.ObtainForCSR(request)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
certsStorage.SaveResource(certRes)
|
||||
|
||||
if ariRenewalTime != nil {
|
||||
// Post to the renewalInfo endpoint to indicate that we have renewed and replaced the certificate.
|
||||
err := client.Certificate.UpdateRenewalInfo(certificate.RenewalInfoRequest{
|
||||
Cert: certificates[0],
|
||||
Issuer: certificates[1],
|
||||
HashName: ctx.String("ari-hash-name"),
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("[%s] Failed to update renewal info: %v", domain, err)
|
||||
}
|
||||
}
|
||||
|
||||
meta[renewEnvCertDomain] = domain
|
||||
meta[renewEnvCertPath] = certsStorage.GetFileName(domain, ".crt")
|
||||
meta[renewEnvCertKeyPath] = certsStorage.GetFileName(domain, ".key")
|
||||
|
||||
return launchHook(ctx.String("renew-hook"), meta)
|
||||
}
|
||||
|
||||
func needRenewal(x509Cert *x509.Certificate, domain string, days int) bool {
|
||||
if x509Cert.IsCA {
|
||||
log.Fatalf("[%s] Certificate bundle starts with a CA certificate", domain)
|
||||
}
|
||||
|
||||
if days >= 0 {
|
||||
notAfter := int(time.Until(x509Cert.NotAfter).Hours() / 24.0)
|
||||
if notAfter > days {
|
||||
log.Printf("[%s] The certificate expires in %d days, the number of days defined to perform the renewal is %d: no renewal.",
|
||||
domain, notAfter, days)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// getARIRenewalTime checks if the certificate needs to be renewed using the renewalInfo endpoint.
|
||||
func getARIRenewalTime(ctx *cli.Context, cert, issuer *x509.Certificate, domain string, client *lego.Client) *time.Time {
|
||||
if cert.IsCA {
|
||||
log.Fatalf("[%s] Certificate bundle starts with a CA certificate", domain)
|
||||
}
|
||||
|
||||
renewalInfo, err := client.Certificate.GetRenewalInfo(certificate.RenewalInfoRequest{
|
||||
Cert: cert,
|
||||
Issuer: issuer,
|
||||
HashName: ctx.String("ari-hash-name"),
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, api.ErrNoARI) {
|
||||
// The server does not advertise a renewal info endpoint.
|
||||
log.Warnf("[%s] acme: %w", domain, err)
|
||||
return nil
|
||||
}
|
||||
log.Warnf("[%s] acme: calling renewal info endpoint: %w", domain, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
renewalTime := renewalInfo.ShouldRenewAt(now, ctx.Duration("ari-wait-to-renew-duration"))
|
||||
if renewalTime == nil {
|
||||
log.Infof("[%s] acme: renewalInfo endpoint indicates that renewal is not needed", domain)
|
||||
return nil
|
||||
}
|
||||
log.Infof("[%s] acme: renewalInfo endpoint indicates that renewal is needed", domain)
|
||||
|
||||
if renewalInfo.ExplanationURL != "" {
|
||||
log.Infof("[%s] acme: renewalInfo endpoint provided an explanation: %s", domain, renewalInfo.ExplanationURL)
|
||||
}
|
||||
|
||||
return renewalTime
|
||||
}
|
||||
|
||||
func merge(prevDomains, nextDomains []string) []string {
|
||||
for _, next := range nextDomains {
|
||||
var found bool
|
||||
for _, prev := range prevDomains {
|
||||
if prev == next {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
prevDomains = append(prevDomains, next)
|
||||
}
|
||||
}
|
||||
return prevDomains
|
||||
}
|
118
cmd/cmd_renew_test.go
Normal file
118
cmd/cmd_renew_test.go
Normal file
|
@ -0,0 +1,118 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_merge(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
prevDomains []string
|
||||
nextDomains []string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
desc: "all empty",
|
||||
prevDomains: []string{},
|
||||
nextDomains: []string{},
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
desc: "next empty",
|
||||
prevDomains: []string{"a", "b", "c"},
|
||||
nextDomains: []string{},
|
||||
expected: []string{"a", "b", "c"},
|
||||
},
|
||||
{
|
||||
desc: "prev empty",
|
||||
prevDomains: []string{},
|
||||
nextDomains: []string{"a", "b", "c"},
|
||||
expected: []string{"a", "b", "c"},
|
||||
},
|
||||
{
|
||||
desc: "merge append",
|
||||
prevDomains: []string{"a", "b", "c"},
|
||||
nextDomains: []string{"a", "c", "d"},
|
||||
expected: []string{"a", "b", "c", "d"},
|
||||
},
|
||||
{
|
||||
desc: "merge same",
|
||||
prevDomains: []string{"a", "b", "c"},
|
||||
nextDomains: []string{"a", "b", "c"},
|
||||
expected: []string{"a", "b", "c"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
actual := merge(test.prevDomains, test.nextDomains)
|
||||
assert.Equal(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_needRenewal(t *testing.T) {
|
||||
testCases := []struct {
|
||||
desc string
|
||||
x509Cert *x509.Certificate
|
||||
days int
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
desc: "30 days, NotAfter now",
|
||||
x509Cert: &x509.Certificate{
|
||||
NotAfter: time.Now(),
|
||||
},
|
||||
days: 30,
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
desc: "30 days, NotAfter 31 days",
|
||||
x509Cert: &x509.Certificate{
|
||||
NotAfter: time.Now().Add(31*24*time.Hour + 1*time.Second),
|
||||
},
|
||||
days: 30,
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
desc: "30 days, NotAfter 30 days",
|
||||
x509Cert: &x509.Certificate{
|
||||
NotAfter: time.Now().Add(30 * 24 * time.Hour),
|
||||
},
|
||||
days: 30,
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
desc: "0 days, NotAfter 30 days: only the day of the expiration",
|
||||
x509Cert: &x509.Certificate{
|
||||
NotAfter: time.Now().Add(30 * 24 * time.Hour),
|
||||
},
|
||||
days: 0,
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
desc: "-1 days, NotAfter 30 days: always renew",
|
||||
x509Cert: &x509.Certificate{
|
||||
NotAfter: time.Now().Add(30 * 24 * time.Hour),
|
||||
},
|
||||
days: -1,
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
actual := needRenewal(test.x509Cert, "foo.com", test.days)
|
||||
|
||||
assert.Equal(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
76
cmd/cmd_revoke.go
Normal file
76
cmd/cmd_revoke.go
Normal file
|
@ -0,0 +1,76 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/go-acme/lego/v4/acme"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func createRevoke() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "revoke",
|
||||
Usage: "Revoke a certificate",
|
||||
Action: revoke,
|
||||
Flags: []cli.Flag{
|
||||
&cli.BoolFlag{
|
||||
Name: "keep",
|
||||
Aliases: []string{"k"},
|
||||
Usage: "Keep the certificates after the revocation instead of archiving them.",
|
||||
},
|
||||
&cli.UintFlag{
|
||||
Name: "reason",
|
||||
Usage: "Identifies the reason for the certificate revocation." +
|
||||
" See https://www.rfc-editor.org/rfc/rfc5280.html#section-5.3.1." +
|
||||
" Valid values are:" +
|
||||
" 0 (unspecified), 1 (keyCompromise), 2 (cACompromise), 3 (affiliationChanged)," +
|
||||
" 4 (superseded), 5 (cessationOfOperation), 6 (certificateHold), 8 (removeFromCRL)," +
|
||||
" 9 (privilegeWithdrawn), or 10 (aACompromise).",
|
||||
Value: acme.CRLReasonUnspecified,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func revoke(ctx *cli.Context) error {
|
||||
acc, client := setup(ctx, NewAccountsStorage(ctx))
|
||||
|
||||
if acc.Registration == nil {
|
||||
log.Fatalf("Account %s is not registered. Use 'run' to register a new account.\n", acc.Email)
|
||||
}
|
||||
|
||||
certsStorage := NewCertificatesStorage(ctx)
|
||||
certsStorage.CreateRootFolder()
|
||||
|
||||
for _, domain := range ctx.StringSlice("domains") {
|
||||
log.Printf("Trying to revoke certificate for domain %s", domain)
|
||||
|
||||
certBytes, err := certsStorage.ReadFile(domain, ".crt")
|
||||
if err != nil {
|
||||
log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
reason := ctx.Uint("reason")
|
||||
|
||||
err = client.Certificate.RevokeWithReason(certBytes, &reason)
|
||||
if err != nil {
|
||||
log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err)
|
||||
}
|
||||
|
||||
log.Println("Certificate was revoked.")
|
||||
|
||||
if ctx.Bool("keep") {
|
||||
return nil
|
||||
}
|
||||
|
||||
certsStorage.CreateArchiveFolder()
|
||||
|
||||
err = certsStorage.MoveToArchive(domain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Println("Certificate was archived for domain:", domain)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
222
cmd/cmd_run.go
Normal file
222
cmd/cmd_run.go
Normal file
|
@ -0,0 +1,222 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/certificate"
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
"github.com/go-acme/lego/v4/log"
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func createRun() *cli.Command {
|
||||
return &cli.Command{
|
||||
Name: "run",
|
||||
Usage: "Register an account, then create and install a certificate",
|
||||
Before: func(ctx *cli.Context) error {
|
||||
// we require either domains or csr, but not both
|
||||
hasDomains := len(ctx.StringSlice("domains")) > 0
|
||||
hasCsr := len(ctx.String("csr")) > 0
|
||||
if hasDomains && hasCsr {
|
||||
log.Fatal("Please specify either --domains/-d or --csr/-c, but not both")
|
||||
}
|
||||
if !hasDomains && !hasCsr {
|
||||
log.Fatal("Please specify --domains/-d (or --csr/-c if you already have a CSR)")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Action: run,
|
||||
Flags: []cli.Flag{
|
||||
&cli.BoolFlag{
|
||||
Name: "no-bundle",
|
||||
Usage: "Do not create a certificate bundle by adding the issuers certificate to the new certificate.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "must-staple",
|
||||
Usage: "Include the OCSP must staple TLS extension in the CSR and generated certificate." +
|
||||
" Only works if the CSR is generated by lego.",
|
||||
},
|
||||
&cli.TimestampFlag{
|
||||
Name: "not-before",
|
||||
Usage: "Set the notBefore field in the certificate (RFC3339 format)",
|
||||
Layout: time.RFC3339,
|
||||
},
|
||||
&cli.TimestampFlag{
|
||||
Name: "not-after",
|
||||
Usage: "Set the notAfter field in the certificate (RFC3339 format)",
|
||||
Layout: time.RFC3339,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "preferred-chain",
|
||||
Usage: "If the CA offers multiple certificate chains, prefer the chain with an issuer matching this Subject Common Name." +
|
||||
" If no match, the default offered chain will be used.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "always-deactivate-authorizations",
|
||||
Usage: "Force the authorizations to be relinquished even if the certificate request was successful.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "run-hook",
|
||||
Usage: "Define a hook. The hook is executed when the certificates are effectively created.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const rootPathWarningMessage = `!!!! HEADS UP !!!!
|
||||
|
||||
Your account credentials have been saved in your Let's Encrypt
|
||||
configuration directory at "%s".
|
||||
|
||||
You should make a secure backup of this folder now. This
|
||||
configuration directory will also contain certificates and
|
||||
private keys obtained from Let's Encrypt so making regular
|
||||
backups of this folder is ideal.
|
||||
`
|
||||
|
||||
func run(ctx *cli.Context) error {
|
||||
accountsStorage := NewAccountsStorage(ctx)
|
||||
|
||||
account, client := setup(ctx, accountsStorage)
|
||||
setupChallenges(ctx, client)
|
||||
|
||||
if account.Registration == nil {
|
||||
reg, err := register(ctx, client)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not complete registration\n\t%v", err)
|
||||
}
|
||||
|
||||
account.Registration = reg
|
||||
if err = accountsStorage.Save(account); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Printf(rootPathWarningMessage, accountsStorage.GetRootPath())
|
||||
}
|
||||
|
||||
certsStorage := NewCertificatesStorage(ctx)
|
||||
certsStorage.CreateRootFolder()
|
||||
|
||||
cert, err := obtainCertificate(ctx, client)
|
||||
if err != nil {
|
||||
// Make sure to return a non-zero exit code if ObtainSANCertificate returned at least one error.
|
||||
// Due to us not returning partial certificate we can just exit here instead of at the end.
|
||||
log.Fatalf("Could not obtain certificates:\n\t%v", err)
|
||||
}
|
||||
|
||||
certsStorage.SaveResource(cert)
|
||||
|
||||
meta := map[string]string{
|
||||
renewEnvAccountEmail: account.Email,
|
||||
renewEnvCertDomain: cert.Domain,
|
||||
renewEnvCertPath: certsStorage.GetFileName(cert.Domain, ".crt"),
|
||||
renewEnvCertKeyPath: certsStorage.GetFileName(cert.Domain, ".key"),
|
||||
renewEnvCertPEMPath: certsStorage.GetFileName(cert.Domain, ".pem"),
|
||||
renewEnvCertPFXPath: certsStorage.GetFileName(cert.Domain, ".pfx"),
|
||||
}
|
||||
|
||||
return launchHook(ctx.String("run-hook"), meta)
|
||||
}
|
||||
|
||||
func handleTOS(ctx *cli.Context, client *lego.Client) bool {
|
||||
// Check for a global accept override
|
||||
if ctx.Bool("accept-tos") {
|
||||
return true
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
log.Printf("Please review the TOS at %s", client.GetToSURL())
|
||||
|
||||
for {
|
||||
fmt.Println("Do you accept the TOS? Y/n")
|
||||
text, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read from console: %v", err)
|
||||
}
|
||||
|
||||
text = strings.Trim(text, "\r\n")
|
||||
switch text {
|
||||
case "", "y", "Y":
|
||||
return true
|
||||
case "n", "N":
|
||||
return false
|
||||
default:
|
||||
fmt.Println("Your input was invalid. Please answer with one of Y/y, n/N or by pressing enter.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func register(ctx *cli.Context, client *lego.Client) (*registration.Resource, error) {
|
||||
accepted := handleTOS(ctx, client)
|
||||
if !accepted {
|
||||
log.Fatal("You did not accept the TOS. Unable to proceed.")
|
||||
}
|
||||
|
||||
if ctx.Bool("eab") {
|
||||
kid := ctx.String("kid")
|
||||
hmacEncoded := ctx.String("hmac")
|
||||
|
||||
if kid == "" || hmacEncoded == "" {
|
||||
log.Fatalf("Requires arguments --kid and --hmac.")
|
||||
}
|
||||
|
||||
return client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
|
||||
TermsOfServiceAgreed: accepted,
|
||||
Kid: kid,
|
||||
HmacEncoded: hmacEncoded,
|
||||
})
|
||||
}
|
||||
|
||||
return client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
}
|
||||
|
||||
func obtainCertificate(ctx *cli.Context, client *lego.Client) (*certificate.Resource, error) {
|
||||
bundle := !ctx.Bool("no-bundle")
|
||||
|
||||
domains := ctx.StringSlice("domains")
|
||||
if len(domains) > 0 {
|
||||
// obtain a certificate, generating a new private key
|
||||
request := certificate.ObtainRequest{
|
||||
Domains: domains,
|
||||
Bundle: bundle,
|
||||
MustStaple: ctx.Bool("must-staple"),
|
||||
PreferredChain: ctx.String("preferred-chain"),
|
||||
AlwaysDeactivateAuthorizations: ctx.Bool("always-deactivate-authorizations"),
|
||||
}
|
||||
|
||||
notBefore := ctx.Timestamp("not-before")
|
||||
if notBefore != nil {
|
||||
request.NotBefore = *notBefore
|
||||
}
|
||||
|
||||
notAfter := ctx.Timestamp("not-after")
|
||||
if notAfter != nil {
|
||||
request.NotAfter = *notAfter
|
||||
}
|
||||
|
||||
return client.Certificate.Obtain(request)
|
||||
}
|
||||
|
||||
// read the CSR
|
||||
csr, err := readCSRFile(ctx.String("csr"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// obtain a certificate for this CSR
|
||||
request := certificate.ObtainForCSRRequest{
|
||||
CSR: csr,
|
||||
NotBefore: getTime(ctx, "not-before"),
|
||||
NotAfter: getTime(ctx, "not-after"),
|
||||
Bundle: bundle,
|
||||
PreferredChain: ctx.String("preferred-chain"),
|
||||
AlwaysDeactivateAuthorizations: ctx.Bool("always-deactivate-authorizations"),
|
||||
}
|
||||
|
||||
return client.Certificate.ObtainForCSR(request)
|
||||
}
|
170
cmd/flags.go
Normal file
170
cmd/flags.go
Normal file
|
@ -0,0 +1,170 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
"github.com/urfave/cli/v2"
|
||||
"software.sslmate.com/src/go-pkcs12"
|
||||
)
|
||||
|
||||
func CreateFlags(defaultPath string) []cli.Flag {
|
||||
return []cli.Flag{
|
||||
&cli.StringSliceFlag{
|
||||
Name: "domains",
|
||||
Aliases: []string{"d"},
|
||||
Usage: "Add a domain to the process. Can be specified multiple times.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "server",
|
||||
Aliases: []string{"s"},
|
||||
Usage: "CA hostname (and optionally :port). The server certificate must be trusted in order to avoid further modifications to the client.",
|
||||
Value: lego.LEDirectoryProduction,
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "accept-tos",
|
||||
Aliases: []string{"a"},
|
||||
Usage: "By setting this flag to true you indicate that you accept the current Let's Encrypt terms of service.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "email",
|
||||
Aliases: []string{"m"},
|
||||
Usage: "Email used for registration and recovery contact.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "csr",
|
||||
Aliases: []string{"c"},
|
||||
Usage: "Certificate signing request filename, if an external CSR is to be used.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "eab",
|
||||
Usage: "Use External Account Binding for account registration. Requires --kid and --hmac.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "kid",
|
||||
Usage: "Key identifier from External CA. Used for External Account Binding.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "hmac",
|
||||
Usage: "MAC key from External CA. Should be in Base64 URL Encoding without padding format. Used for External Account Binding.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "key-type",
|
||||
Aliases: []string{"k"},
|
||||
Value: "ec256",
|
||||
Usage: "Key type to use for private keys. Supported: rsa2048, rsa3072, rsa4096, rsa8192, ec256, ec384.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "filename",
|
||||
Usage: "(deprecated) Filename of the generated certificate.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "path",
|
||||
EnvVars: []string{"LEGO_PATH"},
|
||||
Usage: "Directory to use for storing the data.",
|
||||
Value: defaultPath,
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "http",
|
||||
Usage: "Use the HTTP-01 challenge to solve challenges. Can be mixed with other types of challenges.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "http.port",
|
||||
Usage: "Set the port and interface to use for HTTP-01 based challenges to listen on. Supported: interface:port or :port.",
|
||||
Value: ":80",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "http.proxy-header",
|
||||
Usage: "Validate against this HTTP header when solving HTTP-01 based challenges behind a reverse proxy.",
|
||||
Value: "Host",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "http.webroot",
|
||||
Usage: "Set the webroot folder to use for HTTP-01 based challenges to write directly to the .well-known/acme-challenge file." +
|
||||
" This disables the built-in server and expects the given directory to be publicly served with access to .well-known/acme-challenge",
|
||||
},
|
||||
&cli.StringSliceFlag{
|
||||
Name: "http.memcached-host",
|
||||
Usage: "Set the memcached host(s) to use for HTTP-01 based challenges. Challenges will be written to all specified hosts.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "tls",
|
||||
Usage: "Use the TLS-ALPN-01 challenge to solve challenges. Can be mixed with other types of challenges.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "tls.port",
|
||||
Usage: "Set the port and interface to use for TLS-ALPN-01 based challenges to listen on. Supported: interface:port or :port.",
|
||||
Value: ":443",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "dns",
|
||||
Usage: "Solve a DNS-01 challenge using the specified provider. Can be mixed with other types of challenges. Run 'lego dnshelp' for help on usage.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "dns.disable-cp",
|
||||
Usage: "By setting this flag to true, disables the need to await propagation of the TXT record to all authoritative name servers.",
|
||||
},
|
||||
&cli.StringSliceFlag{
|
||||
Name: "dns.resolvers",
|
||||
Usage: "Set the resolvers to use for performing (recursive) CNAME resolving and apex domain determination." +
|
||||
" For DNS-01 challenge verification, the authoritative DNS server is queried directly." +
|
||||
" Supported: host:port." +
|
||||
" The default is to use the system resolvers, or Google's DNS resolvers if the system's cannot be determined.",
|
||||
},
|
||||
&cli.IntFlag{
|
||||
Name: "http-timeout",
|
||||
Usage: "Set the HTTP timeout value to a specific value in seconds.",
|
||||
},
|
||||
&cli.IntFlag{
|
||||
Name: "dns-timeout",
|
||||
Usage: "Set the DNS timeout value to a specific value in seconds. Used only when performing authoritative name server queries.",
|
||||
Value: 10,
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "pem",
|
||||
Usage: "Generate an additional .pem (base64) file by concatenating the .key and .crt files together.",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "pfx",
|
||||
Usage: "Generate an additional .pfx (PKCS#12) file by concatenating the .key and .crt and issuer .crt files together.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "pfx.pass",
|
||||
Usage: "The password used to encrypt the .pfx (PCKS#12) file.",
|
||||
Value: pkcs12.DefaultPassword,
|
||||
},
|
||||
&cli.IntFlag{
|
||||
Name: "cert.timeout",
|
||||
Usage: "Set the certificate timeout value to a specific value in seconds. Only used when obtaining certificates.",
|
||||
Value: 30,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "user-agent",
|
||||
Usage: "Add to the user-agent sent to the CA to identify an application embedding lego-cli",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "nns",
|
||||
Usage: "Solve a NNS-01 challenge using the specified URL of NNS server.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "wallet",
|
||||
Usage: "Path to wallet file for NNS provider.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "wallet.account-address",
|
||||
Usage: "Address of account to use from wallet file.",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "wallet.password",
|
||||
Usage: "Password to account from wallet file.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getTime(ctx *cli.Context, name string) time.Time {
|
||||
value := ctx.Timestamp(name)
|
||||
if value == nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return *value
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue