-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathnet.nim
2186 lines (1956 loc) · 80.7 KB
/
net.nim
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
#
# Nim's Runtime Library
# (c) Copyright 2015 Dominik Picheta
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## This module implements a high-level cross-platform sockets interface.
## The procedures implemented in this module are primarily for blocking sockets.
## For asynchronous non-blocking sockets use the `asyncnet` module together
## with the `asyncdispatch` module.
##
## The first thing you will always need to do in order to start using sockets,
## is to create a new instance of the `Socket` type using the `newSocket`
## procedure.
##
## SSL
## ====
##
## In order to use the SSL procedures defined in this module, you will need to
## compile your application with the `-d:ssl` flag. See the
## `newContext<net.html#newContext%2Cstring%2Cstring%2Cstring%2Cstring>`_
## procedure for additional details.
##
##
## SSL on Windows
## ==============
##
## On Windows the SSL library checks for valid certificates.
## It uses the `cacert.pem` file for this purpose which was extracted
## from `https://curl.se/ca/cacert.pem`. Besides
## the OpenSSL DLLs (e.g. libssl-1_1-x64.dll, libcrypto-1_1-x64.dll) you
## also need to ship `cacert.pem` with your `.exe` file.
##
##
## Examples
## ========
##
## Connecting to a server
## ----------------------
##
## After you create a socket with the `newSocket` procedure, you can easily
## connect it to a server running at a known hostname (or IP address) and port.
## To do so over TCP, use the example below.
runnableExamples("-r:off"):
let socket = newSocket()
socket.connect("google.com", Port(80))
## For SSL, use the following example:
runnableExamples("-r:off -d:ssl"):
let socket = newSocket()
let ctx = newContext()
wrapSocket(ctx, socket)
socket.connect("google.com", Port(443))
## UDP is a connectionless protocol, so UDP sockets don't have to explicitly
## call the `connect <net.html#connect%2CSocket%2Cstring>`_ procedure. They can
## simply start sending data immediately.
runnableExamples("-r:off"):
let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
socket.sendTo("192.168.0.1", Port(27960), "status\n")
when defined(zephyr):
runnableExamples("-r:off"):
let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
let ip = parseIpAddress("192.168.0.1")
doAssert socket.sendTo(ip, Port(27960), "status\c\l") == 8
## Creating a server
## -----------------
##
## After you create a socket with the `newSocket` procedure, you can create a
## TCP server by calling the `bindAddr` and `listen` procedures.
runnableExamples("-r:off"):
let socket = newSocket()
socket.bindAddr(Port(1234))
socket.listen()
# You can then begin accepting connections using the `accept` procedure.
var client: Socket
var address = ""
while true:
socket.acceptAddr(client, address)
echo "Client connected from: ", address
import std/private/since
import nativesockets
import os, strutils, times, sets, options, std/monotimes
import ssl_config
export nativesockets.Port, nativesockets.`$`, nativesockets.`==`
export Domain, SockType, Protocol
const useWinVersion = defined(windows) or defined(nimdoc)
const useNimNetLite = defined(nimNetLite) or defined(freertos) or defined(zephyr)
const defineSsl = defined(ssl) or defined(nimdoc)
when useWinVersion:
from winlean import WSAESHUTDOWN
when defineSsl:
import openssl
when not defined(nimDisableCertificateValidation):
from ssl_certs import scanSSLCertificates
# Note: The enumerations are mapped to Window's constants.
when defineSsl:
type
Certificate* = string ## DER encoded certificate
SslError* = object of CatchableError
SslCVerifyMode* = enum
CVerifyNone, CVerifyPeer, CVerifyPeerUseEnvVars
SslProtVersion* = enum
protSSLv2, protSSLv3, protTLSv1, protSSLv23
SslContext* = ref object
context*: SslCtx
referencedData: HashSet[int]
extraInternal: SslContextExtraInternal
SslAcceptResult* = enum
AcceptNoClient = 0, AcceptNoHandshake, AcceptSuccess
SslHandshakeType* = enum
handshakeAsClient, handshakeAsServer
SslClientGetPskFunc* = proc(hint: string): tuple[identity: string, psk: string]
SslServerGetPskFunc* = proc(identity: string): string
SslContextExtraInternal = ref object of RootRef
serverGetPskFunc: SslServerGetPskFunc
clientGetPskFunc: SslClientGetPskFunc
else:
type
SslContext* = ref object # TODO: Workaround #4797.
const
BufferSize*: int = 4000 ## size of a buffered socket's buffer
MaxLineLength* = 1_000_000
type
SocketImpl* = object ## socket type
fd: SocketHandle
isBuffered: bool # determines whether this socket is buffered.
buffer: array[0..BufferSize, char]
currPos: int # current index in buffer
bufLen: int # current length of buffer
when defineSsl:
isSsl: bool
sslHandle: SslPtr
sslContext: SslContext
sslNoHandshake: bool # True if needs handshake.
sslHasPeekChar: bool
sslPeekChar: char
sslNoShutdown: bool # True if shutdown shouldn't be done.
lastError: OSErrorCode ## stores the last error on this socket
domain: Domain
sockType: SockType
protocol: Protocol
Socket* = ref SocketImpl
SOBool* = enum ## Boolean socket options.
OptAcceptConn, OptBroadcast, OptDebug, OptDontRoute, OptKeepAlive,
OptOOBInline, OptReuseAddr, OptReusePort, OptNoDelay
ReadLineResult* = enum ## result for readLineAsync
ReadFullLine, ReadPartialLine, ReadDisconnected, ReadNone
TimeoutError* = object of CatchableError
SocketFlag* {.pure.} = enum
Peek,
SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown.
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
type
IpAddressFamily* {.pure.} = enum ## Describes the type of an IP address
IPv6, ## IPv6 address
IPv4 ## IPv4 address
IpAddress* = object ## stores an arbitrary IP address
case family*: IpAddressFamily ## the type of the IP address (IPv4 or IPv6)
of IpAddressFamily.IPv6:
address_v6*: array[0..15, uint8] ## Contains the IP address in bytes in
## case of IPv6
of IpAddressFamily.IPv4:
address_v4*: array[0..3, uint8] ## Contains the IP address in bytes in
## case of IPv4
when defined(nimHasStyleChecks):
{.pop.}
when defined(posix) and not defined(lwip):
from posix import TPollfd, POLLIN, POLLPRI, POLLOUT, POLLWRBAND, Tnfds
template monitorPollEvent(x: var SocketHandle, y: cint, timeout: int): int =
var tpollfd: TPollfd
tpollfd.fd = cast[cint](x)
tpollfd.events = y
posix.poll(addr(tpollfd), Tnfds(1), timeout)
proc timeoutRead(fd: var SocketHandle, timeout = 500): int =
when defined(windows) or defined(lwip):
var fds = @[fd]
selectRead(fds, timeout)
else:
monitorPollEvent(fd, POLLIN or POLLPRI, timeout)
proc timeoutWrite(fd: var SocketHandle, timeout = 500): int =
when defined(windows) or defined(lwip):
var fds = @[fd]
selectWrite(fds, timeout)
else:
monitorPollEvent(fd, POLLOUT or POLLWRBAND, timeout)
proc socketError*(socket: Socket, err: int = -1, async = false,
lastError = (-1).OSErrorCode,
flags: set[SocketFlag] = {}) {.gcsafe.}
proc isDisconnectionError*(flags: set[SocketFlag],
lastError: OSErrorCode): bool =
## Determines whether `lastError` is a disconnection error. Only does this
## if flags contains `SafeDisconn`.
when useWinVersion:
SocketFlag.SafeDisconn in flags and
(lastError.int32 == WSAECONNRESET or
lastError.int32 == WSAECONNABORTED or
lastError.int32 == WSAENETRESET or
lastError.int32 == WSAEDISCON or
lastError.int32 == WSAESHUTDOWN or
lastError.int32 == ERROR_NETNAME_DELETED)
else:
SocketFlag.SafeDisconn in flags and
(lastError.int32 == ECONNRESET or
lastError.int32 == EPIPE or
lastError.int32 == ENETRESET)
proc toOSFlags*(socketFlags: set[SocketFlag]): cint =
## Converts the flags into the underlying OS representation.
for f in socketFlags:
case f
of SocketFlag.Peek:
result = result or MSG_PEEK
of SocketFlag.SafeDisconn: continue
proc newSocket*(fd: SocketHandle, domain: Domain = AF_INET,
sockType: SockType = SOCK_STREAM,
protocol: Protocol = IPPROTO_TCP, buffered = true): owned(Socket) =
## Creates a new socket as specified by the params.
assert fd != osInvalidSocket
result = Socket(
fd: fd,
isBuffered: buffered,
domain: domain,
sockType: sockType,
protocol: protocol)
if buffered:
result.currPos = 0
# Set SO_NOSIGPIPE on OS X.
when defined(macosx) and not defined(nimdoc):
setSockOptInt(fd, SOL_SOCKET, SO_NOSIGPIPE, 1)
proc newSocket*(domain, sockType, protocol: cint, buffered = true,
inheritable = defined(nimInheritHandles)): owned(Socket) =
## Creates a new socket.
##
## The SocketHandle associated with the resulting Socket will not be
## inheritable by child processes by default. This can be changed via
## the `inheritable` parameter.
##
## If an error occurs OSError will be raised.
let fd = createNativeSocket(domain, sockType, protocol, inheritable)
if fd == osInvalidSocket:
raiseOSError(osLastError())
result = newSocket(fd, domain.Domain, sockType.SockType, protocol.Protocol,
buffered)
proc newSocket*(domain: Domain = AF_INET, sockType: SockType = SOCK_STREAM,
protocol: Protocol = IPPROTO_TCP, buffered = true,
inheritable = defined(nimInheritHandles)): owned(Socket) =
## Creates a new socket.
##
## The SocketHandle associated with the resulting Socket will not be
## inheritable by child processes by default. This can be changed via
## the `inheritable` parameter.
##
## If an error occurs OSError will be raised.
let fd = createNativeSocket(domain, sockType, protocol, inheritable)
if fd == osInvalidSocket:
raiseOSError(osLastError())
result = newSocket(fd, domain, sockType, protocol, buffered)
proc parseIPv4Address(addressStr: string): IpAddress =
## Parses IPv4 addresses
## Raises ValueError on errors
var
byteCount = 0
currentByte: uint16 = 0
separatorValid = false
leadingZero = false
result = IpAddress(family: IpAddressFamily.IPv4)
for i in 0 .. high(addressStr):
if addressStr[i] in strutils.Digits: # Character is a number
if leadingZero:
raise newException(ValueError,
"Invalid IP address. Octal numbers are not allowed")
currentByte = currentByte * 10 +
cast[uint16](ord(addressStr[i]) - ord('0'))
if currentByte == 0'u16:
leadingZero = true
elif currentByte > 255'u16:
raise newException(ValueError,
"Invalid IP Address. Value is out of range")
separatorValid = true
elif addressStr[i] == '.': # IPv4 address separator
if not separatorValid or byteCount >= 3:
raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
result.address_v4[byteCount] = cast[uint8](currentByte)
currentByte = 0
byteCount.inc
separatorValid = false
leadingZero = false
else:
raise newException(ValueError,
"Invalid IP Address. Address contains an invalid character")
if byteCount != 3 or not separatorValid:
raise newException(ValueError, "Invalid IP Address")
result.address_v4[byteCount] = cast[uint8](currentByte)
proc parseIPv6Address(addressStr: string): IpAddress =
## Parses IPv6 addresses
## Raises ValueError on errors
result = IpAddress(family: IpAddressFamily.IPv6)
if addressStr.len < 2:
raise newException(ValueError, "Invalid IP Address")
var
groupCount = 0
currentGroupStart = 0
currentShort: uint32 = 0
separatorValid = true
dualColonGroup = -1
lastWasColon = false
v4StartPos = -1
byteCount = 0
for i, c in addressStr:
if c == ':':
if not separatorValid:
raise newException(ValueError,
"Invalid IP Address. Address contains an invalid separator")
if lastWasColon:
if dualColonGroup != -1:
raise newException(ValueError,
"Invalid IP Address. Address contains more than one \"::\" separator")
dualColonGroup = groupCount
separatorValid = false
elif i != 0 and i != high(addressStr):
if groupCount >= 8:
raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
result.address_v6[groupCount*2] = cast[uint8](currentShort shr 8)
result.address_v6[groupCount*2+1] = cast[uint8](currentShort and 0xFF)
currentShort = 0
groupCount.inc()
if dualColonGroup != -1: separatorValid = false
elif i == 0: # only valid if address starts with ::
if addressStr[1] != ':':
raise newException(ValueError,
"Invalid IP Address. Address may not start with \":\"")
else: # i == high(addressStr) - only valid if address ends with ::
if addressStr[high(addressStr)-1] != ':':
raise newException(ValueError,
"Invalid IP Address. Address may not end with \":\"")
lastWasColon = true
currentGroupStart = i + 1
elif c == '.': # Switch to parse IPv4 mode
if i < 3 or not separatorValid or groupCount >= 7:
raise newException(ValueError, "Invalid IP Address")
v4StartPos = currentGroupStart
currentShort = 0
separatorValid = false
break
elif c in strutils.HexDigits:
if c in strutils.Digits: # Normal digit
currentShort = (currentShort shl 4) + cast[uint32](ord(c) - ord('0'))
elif c >= 'a' and c <= 'f': # Lower case hex
currentShort = (currentShort shl 4) + cast[uint32](ord(c) - ord('a')) + 10
else: # Upper case hex
currentShort = (currentShort shl 4) + cast[uint32](ord(c) - ord('A')) + 10
if currentShort > 65535'u32:
raise newException(ValueError,
"Invalid IP Address. Value is out of range")
lastWasColon = false
separatorValid = true
else:
raise newException(ValueError,
"Invalid IP Address. Address contains an invalid character")
if v4StartPos == -1: # Don't parse v4. Copy the remaining v6 stuff
if separatorValid: # Copy remaining data
if groupCount >= 8:
raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
result.address_v6[groupCount*2] = cast[uint8](currentShort shr 8)
result.address_v6[groupCount*2+1] = cast[uint8](currentShort and 0xFF)
groupCount.inc()
else: # Must parse IPv4 address
var leadingZero = false
for i, c in addressStr[v4StartPos..high(addressStr)]:
if c in strutils.Digits: # Character is a number
if leadingZero:
raise newException(ValueError,
"Invalid IP address. Octal numbers not allowed")
currentShort = currentShort * 10 + cast[uint32](ord(c) - ord('0'))
if currentShort == 0'u32:
leadingZero = true
elif currentShort > 255'u32:
raise newException(ValueError,
"Invalid IP Address. Value is out of range")
separatorValid = true
elif c == '.': # IPv4 address separator
if not separatorValid or byteCount >= 3:
raise newException(ValueError, "Invalid IP Address")
result.address_v6[groupCount*2 + byteCount] = cast[uint8](currentShort)
currentShort = 0
byteCount.inc()
separatorValid = false
leadingZero = false
else: # Invalid character
raise newException(ValueError,
"Invalid IP Address. Address contains an invalid character")
if byteCount != 3 or not separatorValid:
raise newException(ValueError, "Invalid IP Address")
result.address_v6[groupCount*2 + byteCount] = cast[uint8](currentShort)
groupCount += 2
# Shift and fill zeros in case of ::
if groupCount > 8:
raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
elif groupCount < 8: # must fill
if dualColonGroup == -1:
raise newException(ValueError,
"Invalid IP Address. The address consists of too few groups")
var toFill = 8 - groupCount # The number of groups to fill
var toShift = groupCount - dualColonGroup # Nr of known groups after ::
for i in 0..2*toShift-1: # shift
result.address_v6[15-i] = result.address_v6[groupCount*2-i-1]
for i in 0..2*toFill-1: # fill with 0s
result.address_v6[dualColonGroup*2+i] = 0
elif dualColonGroup != -1:
raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
proc parseIpAddress*(addressStr: string): IpAddress =
## Parses an IP address
##
## Raises ValueError on error.
##
## For IPv4 addresses, only the strict form as
## defined in RFC 6943 is considered valid, see
## https://datatracker.ietf.org/doc/html/rfc6943#section-3.1.1.
if addressStr.len == 0:
raise newException(ValueError, "IP Address string is empty")
if addressStr.contains(':'):
return parseIPv6Address(addressStr)
else:
return parseIPv4Address(addressStr)
proc isIpAddress*(addressStr: string): bool {.tags: [].} =
## Checks if a string is an IP address
## Returns true if it is, false otherwise
try:
discard parseIpAddress(addressStr)
except ValueError:
return false
return true
proc toSockAddr*(address: IpAddress, port: Port, sa: var Sockaddr_storage,
sl: var SockLen) =
## Converts `IpAddress` and `Port` to `SockAddr` and `SockLen`
let port = htons(uint16(port))
case address.family
of IpAddressFamily.IPv4:
sl = sizeof(Sockaddr_in).SockLen
let s = cast[ptr Sockaddr_in](addr sa)
s.sin_family = typeof(s.sin_family)(toInt(AF_INET))
s.sin_port = port
copyMem(addr s.sin_addr, unsafeAddr address.address_v4[0],
sizeof(s.sin_addr))
of IpAddressFamily.IPv6:
sl = sizeof(Sockaddr_in6).SockLen
let s = cast[ptr Sockaddr_in6](addr sa)
s.sin6_family = typeof(s.sin6_family)(toInt(AF_INET6))
s.sin6_port = port
copyMem(addr s.sin6_addr, unsafeAddr address.address_v6[0],
sizeof(s.sin6_addr))
proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: SockLen,
address: var IpAddress, port: var Port) =
if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).SockLen:
address = IpAddress(family: IpAddressFamily.IPv4)
let s = cast[ptr Sockaddr_in](sa)
copyMem(addr address.address_v4[0], addr s.sin_addr,
sizeof(address.address_v4))
port = ntohs(s.sin_port).Port
elif sa.ss_family.cint == toInt(AF_INET6) and
sl == sizeof(Sockaddr_in6).SockLen:
address = IpAddress(family: IpAddressFamily.IPv6)
let s = cast[ptr Sockaddr_in6](sa)
copyMem(addr address.address_v6[0], addr s.sin6_addr,
sizeof(address.address_v6))
port = ntohs(s.sin6_port).Port
else:
raise newException(ValueError, "Neither IPv4 nor IPv6")
proc fromSockAddr*(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6,
sl: SockLen, address: var IpAddress, port: var Port) {.inline.} =
## Converts `SockAddr` and `SockLen` to `IpAddress` and `Port`. Raises
## `ObjectConversionDefect` in case of invalid `sa` and `sl` arguments.
fromSockAddrAux(cast[ptr Sockaddr_storage](unsafeAddr sa), sl, address, port)
when defineSsl:
# OpenSSL >= 1.1.0 does not need explicit init.
when not useOpenssl3:
CRYPTO_malloc_init()
doAssert SslLibraryInit() == 1
SSL_load_error_strings()
ERR_load_BIO_strings()
OpenSSL_add_all_algorithms()
proc sslHandle*(self: Socket): SslPtr =
## Retrieve the ssl pointer of `socket`.
## Useful for interfacing with `openssl`.
self.sslHandle
proc raiseSSLError*(s = "") {.raises: [SslError].}=
## Raises a new SSL error.
if s != "":
raise newException(SslError, s)
let err = ERR_peek_last_error()
if err == 0:
raise newException(SslError, "No error reported.")
var errStr = $ERR_error_string(err, nil)
case err
of 336032814, 336032784:
errStr = "Please upgrade your OpenSSL library, it does not support the " &
"necessary protocols. OpenSSL error is: " & errStr
else:
discard
raise newException(SslError, errStr)
proc getExtraData*(ctx: SslContext, index: int): RootRef =
## Retrieves arbitrary data stored inside SslContext.
if index notin ctx.referencedData:
raise newException(IndexDefect, "No data with that index.")
let res = ctx.context.SSL_CTX_get_ex_data(index.cint)
if cast[int](res) == 0:
raiseSSLError()
return cast[RootRef](res)
proc setExtraData*(ctx: SslContext, index: int, data: RootRef) =
## Stores arbitrary data inside SslContext. The unique `index`
## should be retrieved using getSslContextExtraDataIndex.
if index in ctx.referencedData:
GC_unref(getExtraData(ctx, index))
if ctx.context.SSL_CTX_set_ex_data(index.cint, cast[pointer](data)) == -1:
raiseSSLError()
if index notin ctx.referencedData:
ctx.referencedData.incl(index)
GC_ref(data)
# http://simplestcodings.blogspot.co.uk/2010/08/secure-server-client-using-openssl-in-c.html
proc loadCertificates(ctx: SslCtx, certFile, keyFile: string) =
if certFile != "" and not fileExists(certFile):
raise newException(system.IOError,
"Certificate file could not be found: " & certFile)
if keyFile != "" and not fileExists(keyFile):
raise newException(system.IOError, "Key file could not be found: " & keyFile)
if certFile != "":
var ret = SSL_CTX_use_certificate_chain_file(ctx, certFile)
if ret != 1:
raiseSSLError()
# TODO: Password? www.rtfm.com/openssl-examples/part1.pdf
if keyFile != "":
if SSL_CTX_use_PrivateKey_file(ctx, keyFile,
SSL_FILETYPE_PEM) != 1:
raiseSSLError()
if SSL_CTX_check_private_key(ctx) != 1:
raiseSSLError("Verification of private key file failed.")
proc newContext*(protVersion = protSSLv23, verifyMode = CVerifyPeer,
certFile = "", keyFile = "", cipherList = CiphersIntermediate,
caDir = "", caFile = "", ciphersuites = CiphersModern): SslContext =
## Creates an SSL context.
##
## Protocol version is currently ignored by default and TLS is used.
## With `-d:openssl10`, only SSLv23 and TLSv1 may be used.
##
## There are three options for verify mode:
## `CVerifyNone`: certificates are not verified;
## `CVerifyPeer`: certificates are verified;
## `CVerifyPeerUseEnvVars`: certificates are verified and the optional
## environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to
## locate certificates
##
## The `nimDisableCertificateValidation` define overrides verifyMode and
## disables certificate verification globally!
##
## CA certificates will be loaded, in the following order, from:
##
## - caFile, caDir, parameters, if set
## - if `verifyMode` is set to `CVerifyPeerUseEnvVars`,
## the SSL_CERT_FILE and SSL_CERT_DIR environment variables are used
## - a set of files and directories from the `ssl_certs <ssl_certs.html>`_ file.
##
## The last two parameters specify the certificate file path and the key file
## path, a server socket will most likely not work without these.
##
## Certificates can be generated using the following command:
## - `openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout mykey.pem -out mycert.pem`
## or using ECDSA:
## - `openssl ecparam -out mykey.pem -name secp256k1 -genkey`
## - `openssl req -new -key mykey.pem -x509 -nodes -days 365 -out mycert.pem`
var mtd: PSSL_METHOD
when defined(openssl10):
case protVersion
of protSSLv23:
mtd = SSLv23_method()
of protSSLv2:
raiseSSLError("SSLv2 is no longer secure and has been deprecated, use protSSLv23")
of protSSLv3:
raiseSSLError("SSLv3 is no longer secure and has been deprecated, use protSSLv23")
of protTLSv1:
mtd = TLSv1_method()
else:
mtd = TLS_method()
if mtd == nil:
raiseSSLError("Failed to create TLS context")
var newCTX = SSL_CTX_new(mtd)
if newCTX == nil:
raiseSSLError("Failed to create TLS context")
if newCTX.SSL_CTX_set_cipher_list(cipherList) != 1:
raiseSSLError()
when not defined(openssl10) and not defined(libressl):
let sslVersion = getOpenSSLVersion()
if sslVersion >= 0x010101000 and sslVersion != 0x020000000:
# In OpenSSL >= 1.1.1, TLSv1.3 cipher suites can only be configured via
# this API.
if newCTX.SSL_CTX_set_ciphersuites(ciphersuites) != 1:
raiseSSLError()
# Automatically the best ECDH curve for client exchange. Without this, ECDH
# ciphers will be ignored by the server.
#
# From OpenSSL >= 1.1.0, this setting is set by default and can't be
# overriden.
if newCTX.SSL_CTX_set_ecdh_auto(1) != 1:
raiseSSLError()
when defined(nimDisableCertificateValidation):
newCTX.SSL_CTX_set_verify(SSL_VERIFY_NONE, nil)
else:
case verifyMode
of CVerifyPeer, CVerifyPeerUseEnvVars:
newCTX.SSL_CTX_set_verify(SSL_VERIFY_PEER, nil)
of CVerifyNone:
newCTX.SSL_CTX_set_verify(SSL_VERIFY_NONE, nil)
if newCTX == nil:
raiseSSLError()
discard newCTX.SSLCTXSetMode(SSL_MODE_AUTO_RETRY)
newCTX.loadCertificates(certFile, keyFile)
const VerifySuccess = 1 # SSL_CTX_load_verify_locations returns 1 on success.
when not defined(nimDisableCertificateValidation):
if verifyMode != CVerifyNone:
# Use the caDir and caFile parameters if set
if caDir != "" or caFile != "":
if newCTX.SSL_CTX_load_verify_locations(if caFile == "": nil else: caFile.cstring, if caDir == "": nil else: caDir.cstring) != VerifySuccess:
raise newException(IOError, "Failed to load SSL/TLS CA certificate(s).")
else:
# Scan for certs in known locations. For CVerifyPeerUseEnvVars also scan
# the SSL_CERT_FILE and SSL_CERT_DIR env vars
var found = false
for fn in scanSSLCertificates():
if newCTX.SSL_CTX_load_verify_locations(fn, nil) == VerifySuccess:
found = true
break
if not found:
raise newException(IOError, "No SSL/TLS CA certificates found.")
result = SslContext(context: newCTX, referencedData: initHashSet[int](),
extraInternal: new(SslContextExtraInternal))
proc getExtraInternal(ctx: SslContext): SslContextExtraInternal =
return ctx.extraInternal
proc destroyContext*(ctx: SslContext) =
## Free memory referenced by SslContext.
# We assume here that OpenSSL's internal indexes increase by 1 each time.
# That means we can assume that the next internal index is the length of
# extra data indexes.
for i in ctx.referencedData:
GC_unref(getExtraData(ctx, i))
ctx.context.SSL_CTX_free()
proc `pskIdentityHint=`*(ctx: SslContext, hint: string) =
## Sets the identity hint passed to server.
##
## Only used in PSK ciphersuites.
if ctx.context.SSL_CTX_use_psk_identity_hint(hint) <= 0:
raiseSSLError()
proc clientGetPskFunc*(ctx: SslContext): SslClientGetPskFunc =
return ctx.getExtraInternal().clientGetPskFunc
proc pskClientCallback(ssl: SslPtr; hint: cstring; identity: cstring;
max_identity_len: cuint; psk: ptr uint8;
max_psk_len: cuint): cuint {.cdecl.} =
let ctx = SslContext(context: ssl.SSL_get_SSL_CTX)
let hintString = if hint == nil: "" else: $hint
let (identityString, pskString) = (ctx.clientGetPskFunc)(hintString)
if pskString.len.cuint > max_psk_len:
return 0
if identityString.len.cuint >= max_identity_len:
return 0
copyMem(identity, identityString.cstring, identityString.len + 1) # with the last zero byte
copyMem(psk, pskString.cstring, pskString.len)
return pskString.len.cuint
proc `clientGetPskFunc=`*(ctx: SslContext, fun: SslClientGetPskFunc) =
## Sets function that returns the client identity and the PSK based on identity
## hint from the server.
##
## Only used in PSK ciphersuites.
ctx.getExtraInternal().clientGetPskFunc = fun
ctx.context.SSL_CTX_set_psk_client_callback(
if fun == nil: nil else: pskClientCallback)
proc serverGetPskFunc*(ctx: SslContext): SslServerGetPskFunc =
return ctx.getExtraInternal().serverGetPskFunc
proc pskServerCallback(ssl: SslCtx; identity: cstring; psk: ptr uint8;
max_psk_len: cint): cuint {.cdecl.} =
let ctx = SslContext(context: ssl.SSL_get_SSL_CTX)
let pskString = (ctx.serverGetPskFunc)($identity)
if pskString.len.cint > max_psk_len:
return 0
copyMem(psk, pskString.cstring, pskString.len)
return pskString.len.cuint
proc `serverGetPskFunc=`*(ctx: SslContext, fun: SslServerGetPskFunc) =
## Sets function that returns PSK based on the client identity.
##
## Only used in PSK ciphersuites.
ctx.getExtraInternal().serverGetPskFunc = fun
ctx.context.SSL_CTX_set_psk_server_callback(if fun == nil: nil
else: pskServerCallback)
proc getPskIdentity*(socket: Socket): string =
## Gets the PSK identity provided by the client.
assert socket.isSsl
return $(socket.sslHandle.SSL_get_psk_identity)
proc wrapSocket*(ctx: SslContext, socket: Socket) =
## Wraps a socket in an SSL context. This function effectively turns
## `socket` into an SSL socket.
##
## This must be called on an unconnected socket; an SSL session will
## be started when the socket is connected.
##
## FIXME:
## **Disclaimer**: This code is not well tested, may be very unsafe and
## prone to security vulnerabilities.
assert(not socket.isSsl)
socket.isSsl = true
socket.sslContext = ctx
socket.sslHandle = SSL_new(socket.sslContext.context)
socket.sslNoHandshake = false
socket.sslHasPeekChar = false
socket.sslNoShutdown = false
if socket.sslHandle == nil:
raiseSSLError()
if SSL_set_fd(socket.sslHandle, socket.fd) != 1:
raiseSSLError()
proc checkCertName(socket: Socket, hostname: string) {.raises: [SslError], tags:[RootEffect].} =
## Check if the certificate Subject Alternative Name (SAN) or Subject CommonName (CN) matches hostname.
## Wildcards match only in the left-most label.
## When name starts with a dot it will be matched by a certificate valid for any subdomain
when not defined(nimDisableCertificateValidation) and not defined(windows):
assert socket.isSsl
try:
let certificate = socket.sslHandle.SSL_get_peer_certificate()
if certificate.isNil:
raiseSSLError("No SSL certificate found.")
const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT = 0x1.cuint
# https://www.openssl.org/docs/man1.1.1/man3/X509_check_host.html
let match = certificate.X509_check_host(hostname.cstring, hostname.len.cint,
X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, nil)
# https://www.openssl.org/docs/man1.1.1/man3/SSL_get_peer_certificate.html
X509_free(certificate)
if match != 1:
raiseSSLError("SSL Certificate check failed.")
except LibraryError:
raiseSSLError("SSL import failed")
proc wrapConnectedSocket*(ctx: SslContext, socket: Socket,
handshake: SslHandshakeType,
hostname: string = "") =
## Wraps a connected socket in an SSL context. This function effectively
## turns `socket` into an SSL socket.
## `hostname` should be specified so that the client knows which hostname
## the server certificate should be validated against.
##
## This should be called on a connected socket, and will perform
## an SSL handshake immediately.
##
## FIXME:
## **Disclaimer**: This code is not well tested, may be very unsafe and
## prone to security vulnerabilities.
wrapSocket(ctx, socket)
case handshake
of handshakeAsClient:
if hostname.len > 0 and not isIpAddress(hostname):
# Discard result in case OpenSSL version doesn't support SNI, or we're
# not using TLSv1+
discard SSL_set_tlsext_host_name(socket.sslHandle, hostname)
ErrClearError()
let ret = SSL_connect(socket.sslHandle)
socketError(socket, ret)
when not defined(nimDisableCertificateValidation) and not defined(windows):
# FIXME: this should be skipped on CVerifyNone
if hostname.len > 0 and not isIpAddress(hostname):
socket.checkCertName(hostname)
of handshakeAsServer:
ErrClearError()
let ret = SSL_accept(socket.sslHandle)
socketError(socket, ret)
proc getPeerCertificates*(sslHandle: SslPtr): seq[Certificate] {.since: (1, 1).} =
## Returns the certificate chain received by the peer we are connected to
## through the OpenSSL connection represented by `sslHandle`.
## The handshake must have been completed and the certificate chain must
## have been verified successfully or else an empty sequence is returned.
## The chain is ordered from leaf certificate to root certificate.
result = newSeq[Certificate]()
if SSL_get_verify_result(sslHandle) != X509_V_OK:
return
let stack = SSL_get0_verified_chain(sslHandle)
if stack == nil:
return
let length = OPENSSL_sk_num(stack)
if length == 0:
return
for i in 0 .. length - 1:
let x509 = cast[PX509](OPENSSL_sk_value(stack, i))
result.add(i2d_X509(x509))
proc getPeerCertificates*(socket: Socket): seq[Certificate] {.since: (1, 1).} =
## Returns the certificate chain received by the peer we are connected to
## through the given socket.
## The handshake must have been completed and the certificate chain must
## have been verified successfully or else an empty sequence is returned.
## The chain is ordered from leaf certificate to root certificate.
if not socket.isSsl:
result = newSeq[Certificate]()
else:
result = getPeerCertificates(socket.sslHandle)
proc `sessionIdContext=`*(ctx: SslContext, sidCtx: string) =
## Sets the session id context in which a session can be reused.
## Used for permitting clients to reuse a session id instead of
## doing a new handshake.
##
## TLS clients might attempt to resume a session using the session id context,
## thus it must be set if verifyMode is set to CVerifyPeer or CVerifyPeerUseEnvVars,
## otherwise the connection will fail and SslError will be raised if resumption occurs.
##
## - Only useful if set server-side.
## - Should be unique per-application to prevent clients from malfunctioning.
## - sidCtx must be at most 32 characters in length.
if sidCtx.len > 32:
raiseSSLError("sessionIdContext must be shorter than 32 characters")
SSL_CTX_set_session_id_context(ctx.context, sidCtx, sidCtx.len)
proc getSocketError*(socket: Socket): OSErrorCode =
## Checks `osLastError` for a valid error. If it has been reset it uses
## the last error stored in the socket object.
result = osLastError()
if result == 0.OSErrorCode:
result = socket.lastError
if result == 0.OSErrorCode:
raiseOSError(result, "No valid socket error code available")
proc socketError*(socket: Socket, err: int = -1, async = false,
lastError = (-1).OSErrorCode,
flags: set[SocketFlag] = {}) =
## Raises an OSError based on the error code returned by `SSL_get_error`
## (for SSL sockets) and `osLastError` otherwise.
##
## If `async` is `true` no error will be thrown in the case when the
## error was caused by no data being available to be read.
##
## If `err` is not lower than 0 no exception will be raised.
##
## If `flags` contains `SafeDisconn`, no exception will be raised
## when the error was caused by a peer disconnection.
when defineSsl:
if socket.isSsl:
if err <= 0:
var ret = SSL_get_error(socket.sslHandle, err.cint)
case ret
of SSL_ERROR_ZERO_RETURN:
raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
if async:
return
else: raiseSSLError("Not enough data on socket.")
of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ:
if async:
return
else: raiseSSLError("Not enough data on socket.")
of SSL_ERROR_WANT_X509_LOOKUP:
raiseSSLError("Function for x509 lookup has been called.")
of SSL_ERROR_SYSCALL:
# SSL shutdown must not be done if a fatal error occurred.
socket.sslNoShutdown = true
let osErr = osLastError()
if not flags.isDisconnectionError(osErr):
var errStr = "IO error has occurred "
let sslErr = ERR_peek_last_error()
if sslErr == 0 and err == 0:
errStr.add "because an EOF was observed that violates the protocol"
elif sslErr == 0 and err == -1:
errStr.add "in the BIO layer"
else:
let errStr = $ERR_error_string(sslErr, nil)
raiseSSLError(errStr & ": " & errStr)
raiseOSError(osErr, errStr)
of SSL_ERROR_SSL:
# SSL shutdown must not be done if a fatal error occurred.
socket.sslNoShutdown = true
raiseSSLError()
else: raiseSSLError("Unknown Error")
if err == -1 and not (when defineSsl: socket.isSsl else: false):
var lastE = if lastError.int == -1: getSocketError(socket) else: lastError
if not flags.isDisconnectionError(lastE):
if async:
when useWinVersion:
if lastE.int32 == WSAEWOULDBLOCK:
return
else: raiseOSError(lastE)
else:
if lastE.int32 == EAGAIN or lastE.int32 == EWOULDBLOCK:
return
else: raiseOSError(lastE)
else: raiseOSError(lastE)
proc listen*(socket: Socket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].} =