forked from pion/webrtc
/
dtls.go
262 lines (222 loc) · 6.46 KB
/
dtls.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package dtls
/*
#cgo linux windows pkg-config: libssl libcrypto
#cgo linux CFLAGS: -Wno-deprecated-declarations
#cgo darwin CFLAGS: -I/usr/local/opt/openssl/include -I/usr/local/opt/openssl/include -Wno-deprecated-declarations
#cgo darwin LDFLAGS: -L/usr/local/opt/openssl/lib -L/usr/local/opt/openssl/lib -lssl -lcrypto
#cgo windows CFLAGS: -DWIN32_LEAN_AND_MEAN
#include "dtls.h"
*/
import "C"
import (
"fmt"
"net"
"strconv"
"sync"
"unsafe"
"github.com/pkg/errors"
"golang.org/x/net/ipv4"
)
func init() {
if !C.openssl_global_init() {
panic("Failed to initalize OpenSSL") // nolint
}
}
// ConnectionState determines the DTLS connection state
type ConnectionState uint8
// ConnectionState enums
const (
New ConnectionState = iota + 1
Established
)
func (a ConnectionState) String() string {
switch a {
case New:
return "New"
case Established:
return "Established"
default:
return fmt.Sprintf("Invalid ConnectionState %d", a)
}
}
var listenerMap = make(map[string]*ipv4.PacketConn)
var listenerMapLock = &sync.Mutex{}
//export go_handle_sendto
func go_handle_sendto(rawLocal *C.char, rawRemote *C.char, rawBuf *C.char, rawBufLen C.int) {
local := C.GoString(rawLocal)
remote := C.GoString(rawRemote)
buf := []byte(C.GoStringN(rawBuf, rawBufLen))
C.free(unsafe.Pointer(rawBuf))
listenerMapLock.Lock()
defer listenerMapLock.Unlock()
if conn, ok := listenerMap[local]; ok {
strIP, strPort, err := net.SplitHostPort(remote)
if err != nil {
fmt.Println(err)
return
}
port, err := strconv.Atoi(strPort)
if err != nil {
fmt.Println(err)
return
}
_, err = conn.WriteTo(buf, nil, &net.UDPAddr{IP: net.ParseIP(strIP), Port: port})
if err != nil {
fmt.Println(err)
}
} else {
fmt.Printf("Could not find ipv4.PacketConn for %s \n", local)
}
}
// State represents all the state needed for a DTLS session
type State struct {
sync.Mutex
state ConnectionState
notifier func(ConnectionState)
tlscfg *_Ctype_struct_tlscfg
sslctx *_Ctype_struct_ssl_ctx_st
dtlsSession *_Ctype_struct_dtls_sess
}
// NewState creates a new DTLS session
func NewState(notifier func(ConnectionState)) (s *State, err error) {
s = &State{
tlscfg: C.dtls_build_tlscfg(),
state: New,
notifier: notifier,
}
s.sslctx = C.dtls_build_sslctx(s.tlscfg)
return s, err
}
// Start allocates DTLS/ICE state that is dependent on if we are offering or answering
func (s *State) Start(isOffer bool) {
s.dtlsSession = C.dtls_build_session(s.sslctx, C.bool(isOffer))
}
func (s *State) setState(state ConnectionState) {
if s.state != state {
s.state = state
if s.notifier != nil {
go s.notifier(state)
}
}
}
// Close cleans up the associated OpenSSL resources
func (s *State) Close() {
C.dtls_session_cleanup(s.sslctx, s.dtlsSession, s.tlscfg)
}
// Fingerprint generates a SHA-256 fingerprint of the certificate
func (s *State) Fingerprint() string {
cfg := s.tlscfg
if cfg == nil{
return ""
}
var size uint
var fingerprint [C.EVP_MAX_MD_SIZE]byte
sizePtr := unsafe.Pointer(&size)
fingerprintPtr := unsafe.Pointer(&fingerprint)
if C.X509_digest(cfg.cert, C.EVP_sha256(), (*C.uchar)(fingerprintPtr), (*C.uint)(sizePtr)) == 0{
return ""
}
var hexFingerprint string
for i := uint(0); i < size; i++{
hexFingerprint += fmt.Sprintf("%.2X:", fingerprint[i])
}
hexFingerprint = hexFingerprint[:len(hexFingerprint)-1]
return hexFingerprint
}
// CertPair is the client+server key and profile extracted for SRTP
type CertPair struct {
ClientWriteKey []byte
ServerWriteKey []byte
Profile string
}
// HandleDTLSPacket checks if the packet is a DTLS packet, and if it is passes to the DTLS session
// If there is any data after decoding we pass back to the caller to handler
func (s *State) HandleDTLSPacket(packet []byte, local, remote string) ([]byte, error) {
s.Lock()
defer s.Unlock()
if s.dtlsSession == nil {
return nil, errors.Errorf("Unable to handle DTLS packet, session has not started")
}
rawLocal := C.CString(local)
rawRemote := C.CString(remote)
packetRaw := C.CBytes(packet) // unsafe.Pointer
defer func() {
C.free(unsafe.Pointer(rawLocal))
C.free(unsafe.Pointer(rawRemote))
C.free(packetRaw)
}()
if ret := C.dtls_handle_incoming(s.dtlsSession, packetRaw, C.int(len(packet)), rawLocal, rawRemote); ret != nil {
defer func() {
C.free(ret.buf)
C.free(unsafe.Pointer(ret))
}()
if bool(ret.init) && s.state == New {
s.setState(Established)
}
return C.GoBytes(ret.buf, ret.len), nil
}
return nil, nil
}
// Send takes a un-encrypted packet and sends via DTLS
func (s *State) Send(packet []byte, local, remote string) (bool, error) {
s.Lock()
defer s.Unlock()
if s.dtlsSession == nil {
return false, errors.Errorf("Unable to send via DTLS, session has not started")
}
rawLocal := C.CString(local)
rawRemote := C.CString(remote)
packetRaw := C.CBytes(packet) // unsafe.Pointer
defer func() {
C.free(unsafe.Pointer(rawLocal))
C.free(unsafe.Pointer(rawRemote))
C.free(packetRaw)
}()
return bool(C.dtls_handle_outgoing(s.dtlsSession, packetRaw, C.int(len(packet)), rawLocal, rawRemote)), nil
}
// GetCertPair gets the current CertPair if DTLS has finished
func (s *State) GetCertPair() *CertPair {
s.Lock()
defer s.Unlock()
if s.dtlsSession == nil {
return nil
}
if ret := C.dtls_get_certpair(s.dtlsSession); ret != nil {
defer C.free(unsafe.Pointer(ret))
return &CertPair{
ClientWriteKey: []byte(C.GoStringN(&ret.client_write_key[0], ret.key_length)),
ServerWriteKey: []byte(C.GoStringN(&ret.server_write_key[0], ret.key_length)),
Profile: C.GoString(&ret.profile[0]),
}
}
return nil
}
// DoHandshake sends the DTLS handshake it the remote peer
func (s *State) DoHandshake(local, remote string) {
s.Lock()
defer s.Unlock()
if s.dtlsSession == nil {
return
}
rawLocal := C.CString(local)
rawRemote := C.CString(remote)
defer func() {
C.free(unsafe.Pointer(rawLocal))
C.free(unsafe.Pointer(rawRemote))
}()
C.dtls_do_handshake(s.dtlsSession, rawLocal, rawRemote)
}
// AddListener adds the socket to a map that can be accessed by OpenSSL for sending
// This only needed until DTLS is rewritten in native Go
func AddListener(src string, conn *ipv4.PacketConn) {
listenerMapLock.Lock()
listenerMap[src] = conn
listenerMapLock.Unlock()
}
// RemoveListener removes the socket from a map that can be accessed by OpenSSL for sending
// This only needed until DTLS is rewritten in native Go
func RemoveListener(src string) {
listenerMapLock.Lock()
delete(listenerMap, src)
listenerMapLock.Unlock()
}