Skip to content

Commit 47cf8d4

Browse files
committed
feat: add dtls config
Signed-off-by: 1998-felix <felix.gateru@gmail.com>
1 parent 1a2256f commit 47cf8d4

File tree

12 files changed

+341
-61
lines changed

12 files changed

+341
-61
lines changed

Makefile

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,27 @@
11
# Copyright (c) Abstract Machines
22
# SPDX-License-Identifier: Apache-2.0
33

4-
all:
5-
CGO_ENABLED=0 GOOS=linux go build -ldflags "-s -w" -o build/coap-cli-linux cmd/main.go
6-
CGO_ENABLED=0 GOOS=darwin go build -ldflags "-s -w" -o build/coap-cli-darwin cmd/main.go
7-
CGO_ENABLED=0 GOOS=windows go build -ldflags "-s -w" -o build/coap-cli-windows cmd/main.go
4+
INSTALL_DIR=/usr/local/bin
5+
BUILD_DIR=build
6+
BUILD_FLAGS=-ldflags "-s -w"
7+
8+
.PHONY: all linux darwin windows install install-linux
9+
10+
all: linux darwin windows
11+
12+
linux:
13+
CGO_ENABLED=0 GOOS=linux go build $(BUILD_FLAGS) -o $(BUILD_DIR)/coap-cli-linux cmd/main.go
14+
15+
darwin:
16+
CGO_ENABLED=0 GOOS=darwin go build $(BUILD_FLAGS) -o $(BUILD_DIR)/coap-cli-darwin cmd/main.go
17+
18+
windows:
19+
CGO_ENABLED=0 GOOS=windows go build $(BUILD_FLAGS) -o $(BUILD_DIR)/coap-cli-windows cmd/main.go
20+
21+
install: install-linux
22+
23+
install-linux:
24+
@cp $(BUILD_DIR)/coap-cli-linux $(INSTALL_DIR)/coap-cli || { echo "Installation failed"; exit 1; }
25+
26+
clean:
27+
rm -rf $(BUILD_DIR)/*

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,13 @@ Available Commands:
1818

1919
Flags:
2020
-a, --auth string Auth
21+
-A, --ca-file string Client CA file
22+
-C, --cert-file string Client certificate file
2123
-c, --content-format int Content format (default 50)
2224
-h, --help help for coap-cli
2325
-H, --host string Host (default "localhost")
2426
-k, --keep-alive uint Send a ping after interval seconds of inactivity. If not specified (or 0), keep-alive is disabled (default).
27+
-K, --key-file string Client key file
2528
-m, --max-retries uint32 Max retries for keep alive (default 10)
2629
-O, --options num,text Add option num with contents of text to the request. If the text begins with 0x, then the hex text (two [0-9a-f] per byte) is converted to binary data.
2730
-p, --port string Port (default "5683")
@@ -44,6 +47,10 @@ coap-cli get channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --a
4447
coap-cli get channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --options 6,0x00 --options 15,auth=1e1017e6-dee7-45b4-8a13-00e6afeb66eb
4548
```
4649

50+
```bash
51+
coap-cli get channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --options 6,0x00 --options 15,auth=1e1017e6-dee7-45b4-8a13-00e6afeb66eb --ca-file ssl/certs/ca.crt --cert-file ssl/certs/client.crt --key-file ssl/certs/client.key
52+
```
53+
4754
```bash
4855
coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -d "hello world"
4956
```
@@ -55,3 +62,6 @@ coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --
5562
```bash
5663
coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic -options 15,auth=1e1017e6-dee7-45b4-8a13-00e6afeb66eb -d "hello world" -H 0.0.0.0 -p 5683
5764
```
65+
```bash
66+
coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -d "hello world" --ca-file ssl/certs/ca.crt --cert-file ssl/certs/client.crt --key-file ssl/certs/client.key
67+
```

cmd/main.go

Lines changed: 97 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ package main
55

66
import (
77
"context"
8+
"crypto/tls"
9+
"crypto/x509"
810
"encoding/hex"
11+
"errors"
912
"fmt"
1013
"log"
1114
"os"
@@ -17,25 +20,13 @@ import (
1720

1821
coap "github.com/absmach/coap-cli/coap"
1922
"github.com/fatih/color"
23+
piondtls "github.com/pion/dtls/v2"
2024
coapmsg "github.com/plgd-dev/go-coap/v3/message"
2125
"github.com/plgd-dev/go-coap/v3/message/codes"
2226
"github.com/plgd-dev/go-coap/v3/message/pool"
2327
"github.com/spf13/cobra"
2428
)
2529

26-
var (
27-
host string
28-
port string
29-
contentFormat int
30-
auth string
31-
observe bool
32-
data string
33-
options []string
34-
keepAlive uint64
35-
verbose bool
36-
maxRetries uint32
37-
)
38-
3930
const verboseFmt = `Date: %s
4031
Code: %s
4132
Type: %s
@@ -44,6 +35,8 @@ Message-ID: %d
4435
`
4536

4637
func main() {
38+
req := &request{}
39+
4740
rootCmd := &cobra.Command{
4841
Use: "coap-cli <method> <URL> [options]",
4942
Short: "CLI for CoAP",
@@ -54,46 +47,49 @@ func main() {
5447
Short: "Perform a GET request on a COAP resource",
5548
Example: "coap-cli get channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic -a 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -H localhost -p 5683 -O 17,50 -o \n" +
5649
"coap-cli get channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb --host localhost --port 5683 --options 17,50 --observe",
57-
Run: runCmd(codes.GET),
50+
Run: runCmd(req, codes.GET),
5851
}
59-
getCmd.Flags().BoolVarP(&observe, "observe", "o", false, "Observe resource")
52+
getCmd.Flags().BoolVarP(&req.observe, "observe", "o", false, "Observe resource")
6053

6154
putCmd := &cobra.Command{
6255
Use: "put <url>",
6356
Short: "Perform a PUT request on a COAP resource",
6457
Example: "coap-cli put /test -H coap.me -p 5683 -c 50 -d 'hello, world'\n" +
6558
"coap-cli put /test --host coap.me --port 5683 --content-format 50 --data 'hello, world'",
66-
Run: runCmd(codes.PUT),
59+
Run: runCmd(req, codes.PUT),
6760
}
68-
putCmd.Flags().StringVarP(&data, "data", "d", "", "Data")
61+
putCmd.Flags().StringVarP(&req.data, "data", "d", "", "Data")
6962

7063
postCmd := &cobra.Command{
7164
Use: "post <url>",
7265
Short: "Perform a POST request on a COAP resource",
7366
Example: "coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic -a 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -H localhost -p 5683 -c 50 -d 'hello, world'\n" +
7467
"coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic --auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb --host localhost --port 5683 --content-format 50 --data 'hello, world'",
75-
Run: runCmd(codes.POST),
68+
Run: runCmd(req, codes.POST),
7669
}
77-
postCmd.Flags().StringVarP(&data, "data", "d", "", "Data")
70+
postCmd.Flags().StringVarP(&req.data, "data", "d", "", "Data")
7871

7972
deleteCmd := &cobra.Command{
8073
Use: "delete <url>",
8174
Short: "Perform a DELETE request on a COAP resource",
8275
Example: "coap-cli delete /test -H coap.me -p 5683 -c 50 -d 'hello, world' -O 17,50\n" +
8376
"coap-cli delete /test --host coap.me --port 5683 --content-format 50 --data 'hello, world' --options 17,50",
84-
Run: runCmd(codes.DELETE),
77+
Run: runCmd(req, codes.DELETE),
8578
}
86-
deleteCmd.Flags().StringVarP(&data, "data", "d", "", "Data")
79+
deleteCmd.Flags().StringVarP(&req.data, "data", "d", "", "Data")
8780

8881
rootCmd.AddCommand(getCmd, putCmd, postCmd, deleteCmd)
89-
rootCmd.PersistentFlags().StringVarP(&host, "host", "H", "localhost", "Host")
90-
rootCmd.PersistentFlags().StringVarP(&port, "port", "p", "5683", "Port")
91-
rootCmd.PersistentFlags().StringVarP(&auth, "auth", "a", "", "Auth")
92-
rootCmd.PersistentFlags().IntVarP(&contentFormat, "content-format", "c", 50, "Content format")
93-
rootCmd.PersistentFlags().StringArrayVarP(&options, "options", "O", []string{}, "Add option num with contents of text to the request. If the text begins with 0x, then the hex text (two [0-9a-f] per byte) is converted to binary data.")
94-
rootCmd.PersistentFlags().Uint64VarP(&keepAlive, "keep-alive", "k", 0, "Send a ping after interval seconds of inactivity. If not specified (or 0), keep-alive is disabled (default).")
95-
rootCmd.PersistentFlags().Uint32VarP(&maxRetries, "max-retries", "m", 10, "Max retries for keep alive")
96-
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
82+
rootCmd.PersistentFlags().StringVarP(&req.host, "host", "H", "localhost", "Host")
83+
rootCmd.PersistentFlags().StringVarP(&req.port, "port", "p", "5683", "Port")
84+
rootCmd.PersistentFlags().StringVarP(&req.auth, "auth", "a", "", "Auth")
85+
rootCmd.PersistentFlags().IntVarP(&req.contentFormat, "content-format", "c", 50, "Content format")
86+
rootCmd.PersistentFlags().StringArrayVarP(&req.options, "options", "O", []string{}, "Add option num with contents of text to the request. If the text begins with 0x, then the hex text (two [0-9a-f] per byte) is converted to binary data.")
87+
rootCmd.PersistentFlags().Uint64VarP(&req.keepAlive, "keep-alive", "k", 0, "Send a ping after interval seconds of inactivity. If not specified (or 0), keep-alive is disabled (default).")
88+
rootCmd.PersistentFlags().Uint32VarP(&req.maxRetries, "max-retries", "m", 10, "Max retries for keep alive")
89+
rootCmd.PersistentFlags().BoolVarP(&req.verbose, "verbose", "v", false, "Verbose output")
90+
rootCmd.PersistentFlags().StringVarP(&req.certFile, "cert-file", "C", "", "Client certificate file")
91+
rootCmd.PersistentFlags().StringVarP(&req.keyFile, "key-file", "K", "", "Client key file")
92+
rootCmd.PersistentFlags().StringVarP(&req.clientCAFile, "ca-file", "A", "", "Client CA file")
9793

9894
if err := rootCmd.Execute(); err != nil {
9995
log.Fatalf("Error executing command: %v", err)
@@ -126,14 +122,18 @@ func printMsg(m *pool.Message, verbose bool) {
126122
}
127123
}
128124

129-
func makeRequest(code codes.Code, args []string) {
130-
client, err := coap.NewClient(host+":"+port, keepAlive, maxRetries)
125+
func makeRequest(req *request, args []string) {
126+
dtlsConfig, err := req.createDTLSConfig()
127+
if err != nil {
128+
log.Fatalf("Error creating DTLS config: %v", err)
129+
}
130+
client, err := coap.NewClient(req.host+":"+req.port, req.keepAlive, req.maxRetries, dtlsConfig)
131131
if err != nil {
132132
log.Fatalf("Error coap creating client: %v", err)
133133
}
134134

135135
var opts coapmsg.Options
136-
for _, optString := range options {
136+
for _, optString := range req.options {
137137
opt := strings.Split(optString, ",")
138138
if len(opt) < 2 {
139139
log.Fatal("Invalid option format")
@@ -153,20 +153,20 @@ func makeRequest(code codes.Code, args []string) {
153153
opts = append(opts, coapmsg.Option{ID: coapmsg.OptionID(optId), Value: []byte(opt[1])})
154154
}
155155
}
156-
if auth != "" {
157-
opts = append(opts, coapmsg.Option{ID: coapmsg.URIQuery, Value: []byte("auth=" + auth)})
156+
if req.auth != "" {
157+
opts = append(opts, coapmsg.Option{ID: coapmsg.URIQuery, Value: []byte("auth=" + req.auth)})
158158
}
159159
if opts.HasOption(coapmsg.Observe) {
160-
if value, _ := opts.GetBytes(coapmsg.Observe); len(value) == 1 && value[0] == 0 && !observe {
161-
observe = true
160+
if value, _ := opts.GetBytes(coapmsg.Observe); len(value) == 1 && value[0] == 0 && !req.observe {
161+
req.observe = true
162162
}
163163
}
164164

165-
switch code {
165+
switch req.code {
166166
case codes.GET:
167167
switch {
168-
case observe:
169-
obs, err := client.Receive(args[0], verbose, opts...)
168+
case req.observe:
169+
obs, err := client.Receive(args[0], req.verbose, opts...)
170170
if err != nil {
171171
log.Fatalf("Error observing resource: %v", err)
172172
}
@@ -183,28 +183,79 @@ func makeRequest(code codes.Code, args []string) {
183183
}
184184
log.Fatalf("Observation terminated: %v", err)
185185
default:
186-
res, err := client.Send(args[0], code, coapmsg.MediaType(contentFormat), nil, opts...)
186+
res, err := client.Send(args[0], req.code, coapmsg.MediaType(req.contentFormat), nil, opts...)
187187
if err != nil {
188188
log.Fatalf("Error sending message: %v", err)
189189
}
190-
printMsg(res, verbose)
190+
printMsg(res, req.verbose)
191191
}
192192
default:
193-
pld := strings.NewReader(data)
194-
res, err := client.Send(args[0], code, coapmsg.MediaType(contentFormat), pld, opts...)
193+
pld := strings.NewReader(req.data)
194+
res, err := client.Send(args[0], req.code, coapmsg.MediaType(req.contentFormat), pld, opts...)
195195
if err != nil {
196196
log.Fatalf("Error sending message: %v", err)
197197
}
198-
printMsg(res, verbose)
198+
printMsg(res, req.verbose)
199199
}
200200
}
201201

202-
func runCmd(code codes.Code) func(cmd *cobra.Command, args []string) {
202+
func runCmd(req *request, code codes.Code) func(cmd *cobra.Command, args []string) {
203203
return func(cmd *cobra.Command, args []string) {
204204
if len(args) < 1 {
205205
fmt.Fprintf(os.Stdout, color.YellowString("\nusage: %s\n\n"), cmd.Use)
206206
return
207207
}
208-
makeRequest(code, args)
208+
req.code = code
209+
makeRequest(req, args)
210+
}
211+
}
212+
213+
type request struct {
214+
code codes.Code
215+
host string
216+
port string
217+
contentFormat int
218+
auth string
219+
observe bool
220+
data string
221+
options []string
222+
keepAlive uint64
223+
verbose bool
224+
maxRetries uint32
225+
certFile string
226+
keyFile string
227+
clientCAFile string
228+
}
229+
230+
func (r *request) createDTLSConfig() (*piondtls.Config, error) {
231+
if r.certFile == "" || r.keyFile == "" {
232+
return nil, nil
233+
}
234+
dc := &piondtls.Config{}
235+
cert, err := tls.LoadX509KeyPair(r.certFile, r.keyFile)
236+
if err != nil {
237+
return nil, errors.Join(errors.New("failed to load certificates"), err)
238+
}
239+
dc.Certificates = []tls.Certificate{cert}
240+
rootCA, err := loadCertFile(r.clientCAFile)
241+
if err != nil {
242+
return nil, errors.Join(errors.New("failed to load Client CA"), err)
243+
}
244+
if len(rootCA) > 0 {
245+
if dc.RootCAs == nil {
246+
dc.RootCAs = x509.NewCertPool()
247+
}
248+
if !dc.RootCAs.AppendCertsFromPEM(rootCA) {
249+
return nil, errors.New("failed to append root ca tls.Config")
250+
}
251+
}
252+
dc.InsecureSkipVerify = true
253+
return dc, nil
254+
}
255+
256+
func loadCertFile(certFile string) ([]byte, error) {
257+
if certFile != "" {
258+
return os.ReadFile(certFile)
209259
}
260+
return []byte{}, nil
210261
}

coap/client.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import (
1111
"log"
1212
"time"
1313

14+
piondtls "github.com/pion/dtls/v2"
15+
"github.com/plgd-dev/go-coap/v3/dtls"
1416
"github.com/plgd-dev/go-coap/v3/message"
1517
"github.com/plgd-dev/go-coap/v3/message/codes"
1618
"github.com/plgd-dev/go-coap/v3/message/pool"
@@ -39,12 +41,18 @@ type Client struct {
3941
}
4042

4143
// NewClient returns new CoAP client connecting it to the server.
42-
func NewClient(addr string, keepAlive uint64, maxRetries uint32) (Client, error) {
44+
func NewClient(addr string, keepAlive uint64, maxRetries uint32, dtlsConfig *piondtls.Config) (Client, error) {
4345
var dialOptions []udp.Option
4446
if keepAlive > 0 {
4547
dialOptions = append(dialOptions, options.WithKeepAlive(maxRetries, time.Duration(keepAlive)*time.Second, onInactive))
4648
}
47-
c, err := udp.Dial(addr, dialOptions...)
49+
var c *client.Conn
50+
var err error
51+
if dtlsConfig != nil {
52+
c, err = dtls.Dial(addr, dtlsConfig, dialOptions...)
53+
} else {
54+
c, err = udp.Dial(addr, dialOptions...)
55+
}
4856
if err != nil {
4957
return Client{}, errors.Join(errDialFailed, err)
5058
}

go.mod

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,22 @@ go 1.22
44

55
require (
66
github.com/fatih/color v1.17.0
7+
github.com/pion/dtls/v2 v2.2.8-0.20240501061905-2c36d63320a0
78
github.com/plgd-dev/go-coap/v3 v3.3.4
89
github.com/spf13/cobra v1.8.0
910
)
1011

1112
require (
12-
github.com/mattn/go-colorable v0.1.13 // indirect
13-
github.com/mattn/go-isatty v0.0.20 // indirect
14-
)
15-
16-
require (
13+
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
1714
github.com/dsnet/golib/memfile v1.0.0 // indirect
18-
github.com/fatih/color v1.16.0
1915
github.com/hashicorp/errwrap v1.1.0 // indirect
2016
github.com/hashicorp/go-multierror v1.1.1 // indirect
2117
github.com/inconshreveable/mousetrap v1.1.0 // indirect
2218
github.com/mattn/go-colorable v0.1.13 // indirect
2319
github.com/mattn/go-isatty v0.0.20 // indirect
24-
github.com/pion/dtls/v2 v2.2.8-0.20240501061905-2c36d63320a0 // indirect
2520
github.com/pion/logging v0.2.2 // indirect
2621
github.com/pion/transport/v3 v3.0.2 // indirect
22+
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
2723
github.com/spf13/pflag v1.0.5 // indirect
2824
go.uber.org/atomic v1.11.0 // indirect
2925
golang.org/x/crypto v0.22.0 // indirect

go.sum

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
22
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3-
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
43
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4+
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
5+
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
56
github.com/dsnet/golib/memfile v1.0.0 h1:J9pUspY2bDCbF9o+YGwcf3uG6MdyITfh/Fk3/CaEiFs=
67
github.com/dsnet/golib/memfile v1.0.0/go.mod h1:tXGNW9q3RwvWt1VV2qrRKlSSz0npnh12yftCSCy2T64=
78
github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4=
@@ -26,8 +27,9 @@ github.com/pion/transport/v3 v3.0.2 h1:r+40RJR25S9w3jbA6/5uEPTzcdn7ncyU44RWCbHkL
2627
github.com/pion/transport/v3 v3.0.2/go.mod h1:nIToODoOlb5If2jF9y2Igfx3PFYWfuXi37m0IlWa/D0=
2728
github.com/plgd-dev/go-coap/v3 v3.3.4 h1:clDLFOXXmXfhZqB0eSk6WJs2iYfjC2J22Ixwu5MHiO0=
2829
github.com/plgd-dev/go-coap/v3 v3.3.4/go.mod h1:vxBvAgXxL+Au/58XYTM+8ftqO/ycFC9/Dh+uI72xYjA=
29-
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
3030
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
31+
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
32+
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
3133
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
3234
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
3335
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=

0 commit comments

Comments
 (0)