mirror of
https://gogs.blitter.com/RLabs/xs
synced 2024-08-14 10:26:42 +00:00
Compare commits
388 commits
8162707ffa
...
242d39192c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
242d39192c | ||
|
|
3fc74bae70 | ||
|
|
287f9d1035 | ||
|
|
f2929120b6 | ||
|
|
4e8e064c74 | ||
|
|
c23edc6874 | ||
|
|
3193ede825 | ||
|
|
640e59be4f | ||
|
|
5f42894ac2 | ||
|
|
d0f76fd3b4 | ||
|
|
035df99069 | ||
|
|
0f22f35e7c | ||
|
|
5aca04e1d5 | ||
|
|
569230a2af | ||
|
|
01aa67d1f7 | ||
|
|
7901cd8809 | ||
|
|
611b6853b2 | ||
|
|
61b7a80e00 | ||
|
|
b3a359a84e | ||
|
|
1943b2314a | ||
|
|
499eaa665b | ||
|
|
eb373ff37b | ||
|
|
1b01ed14f2 | ||
|
|
09055dffe6 | ||
|
|
f480c8cf78 | ||
|
|
69a3fb5d08 | ||
|
|
3522976ef7 | ||
|
|
f0a2bb0295 | ||
|
|
1addd18806 | ||
|
|
57b71e7925 | ||
|
|
58c87f7e0e | ||
|
|
769df46fb1 | ||
|
|
51488fab6d | ||
|
|
0962c0b811 | ||
|
|
3bea3e6ebb | ||
|
|
1d30b8582d | ||
|
|
47a3c6f1b8 | ||
|
|
6bb4b90c87 | ||
|
|
531c846899 | ||
|
|
cba36b66f1 | ||
|
|
5448dbc7b9 | ||
|
|
09c2408c06 | ||
|
|
4686361ece | ||
|
|
e803d3da09 | ||
|
|
0c1d5e036e | ||
|
|
3b0ddba7f2 | ||
|
|
b3ebd0db17 | ||
|
|
d1076c9bd9 | ||
|
|
2e16c9a692 | ||
|
|
9d674315f9 | ||
|
|
64a314df11 | ||
|
|
f6910162b4 | ||
|
|
6ac6f02b3b | ||
|
|
f3bf6d9041 | ||
|
|
138f855a82 | ||
|
|
e9aa0072a5 | ||
|
|
8de76520e4 | ||
|
|
e84f432033 | ||
|
|
654de563dc | ||
|
|
733fc46d86 | ||
|
|
d18396f535 | ||
|
|
e320725e07 | ||
|
|
d4a3521437 | ||
|
|
c2c43c1c50 | ||
|
|
9ffeab2456 | ||
|
|
0eb785a9dc | ||
|
|
58652ce935 | ||
|
|
1b964a4066 | ||
|
|
3eee573231 | ||
|
|
d3d7ac9aae | ||
|
|
6c049dde08 | ||
|
|
862c0c3d7f | ||
|
|
15a1a39d81 | ||
|
|
977380e61f | ||
|
|
bebfd1cb1f | ||
|
|
399babd62a | ||
|
|
0303b394c8 | ||
|
|
0933aa4ea5 | ||
|
|
d3ebcab1d4 | ||
|
|
89b6e8bce7 | ||
|
|
eb9ce0e0e2 | ||
|
|
d75b419c7a | ||
|
|
f5be3578a8 | ||
|
|
e55b560230 | ||
|
|
d6cd51c79f | ||
|
|
caac02a77b | ||
|
|
7fe915450b | ||
|
|
3be1243bf9 | ||
|
|
7ce725c7d2 | ||
|
|
4e0ddf282a | ||
|
|
9f956cff62 | ||
|
|
f8f4bcbe77 | ||
|
|
faf4d5c50a | ||
|
|
1f84bc95ff | ||
|
|
d4f50bfdc0 | ||
|
|
9b90c0558e | ||
|
|
8dbb10f324 | ||
|
|
b19687c80b | ||
|
|
423410bb40 | ||
|
|
a990c5e1f3 | ||
|
|
3b73c6d731 | ||
|
|
ba52356e6c | ||
|
|
6483c8cc33 | ||
|
|
ce1adf7a07 | ||
|
|
dc3f6f9bd5 | ||
|
|
c354036952 | ||
|
|
c95794da1f | ||
|
|
d7dbcd8fdf | ||
|
|
c9d478ff30 | ||
|
|
35e23b20ce | ||
|
|
795adf6aa0 | ||
|
|
4c0b3a405d | ||
|
|
2946618a02 | ||
|
|
0146a5f4fb | ||
|
|
06854f7a03 | ||
|
|
2087aab2d5 | ||
|
|
f5480553df | ||
|
|
4648188bdc | ||
|
|
b8d32ed882 | ||
|
|
1aa8a1549b | ||
|
|
9e885d5bd7 | ||
|
|
825429003b | ||
|
|
3a720cfb8e | ||
|
|
78b2006af6 | ||
|
|
8f5366fff4 | ||
|
|
c327b2ec72 | ||
|
|
c4c2e24af1 | ||
|
|
1d4c16dd76 | ||
|
|
3ae48addbc | ||
|
|
54396a4e4b | ||
|
|
c24529a1d4 | ||
|
|
5511fc83cd | ||
|
|
cbf3c77342 | ||
|
|
7e60a395ad | ||
|
|
1bb31c5e28 | ||
|
|
5cf7a0f8b3 | ||
|
|
df84580e63 | ||
|
|
f09d6bbfef | ||
|
|
8920184ae4 | ||
|
|
9a72e02fc0 | ||
|
|
a53ec4ac2d | ||
|
|
306ea64299 | ||
|
|
b1bbd9c587 | ||
|
|
a7c01ccbcd | ||
|
|
5663fd0c79 | ||
|
|
b1e696911f | ||
|
|
8ea0d79070 | ||
|
|
b82eb1fdc8 | ||
|
|
4db668fbb4 | ||
|
|
b32a9e6c1a | ||
|
|
a87c0005c7 | ||
|
|
6c1172b499 | ||
|
|
2f56fff1e6 | ||
|
|
76ce11c263 | ||
|
|
61f12d33bc | ||
|
|
dd13765f16 | ||
|
|
5528fe4a17 | ||
|
|
113721b808 | ||
|
|
ec7d7ca7d1 | ||
|
|
300f3a0dde | ||
|
|
88e697fa1d | ||
|
|
8195c6b5a7 | ||
|
|
ae403c4b54 | ||
|
|
b7e96f8b18 | ||
|
|
537587af5b | ||
|
|
15638889bd | ||
|
|
e714fc43be | ||
|
|
205e68dcf8 | ||
|
|
d5f083c8fb | ||
|
|
2fbf5737ef | ||
|
|
4684be07ff | ||
|
|
8fb2dc275e | ||
|
|
29a8acf2d8 | ||
|
|
e07c5ee996 | ||
|
|
902e150d21 | ||
|
|
0a59bbedc8 | ||
|
|
91fa5fd2d2 | ||
|
|
002a70ea3f | ||
|
|
900cc03302 | ||
|
|
206d18aa15 | ||
|
|
ea01123b87 | ||
|
|
4b059242d9 | ||
|
|
3dab963bc9 | ||
|
|
a0e90c14ba | ||
|
|
9641fd3fff | ||
|
|
43d9b13a08 | ||
|
|
da78f37e42 | ||
|
|
f83cdd23b1 | ||
|
|
55fdffbd9e | ||
|
|
1a294c3ce4 | ||
|
|
df64eda796 | ||
|
|
20dcfd7bb2 | ||
|
|
5ad08fd3b3 | ||
|
|
b4672deded | ||
|
|
291bacf2df | ||
|
|
3e7f143f7b | ||
|
|
b6a22ce64a | ||
|
|
103d76989e | ||
|
|
85619f3cc9 | ||
|
|
556a9fcfd0 | ||
|
|
fc05a9a4a3 | ||
|
|
6fbbcdadb6 | ||
|
|
2da0d8b198 | ||
|
|
5eb80f4226 | ||
|
|
738bcf3ba9 | ||
|
|
fa398159e3 | ||
|
|
729697b5ee | ||
|
|
6c6d0cbbb6 | ||
|
|
0b668630e7 | ||
|
|
c6cbd8d681 | ||
|
|
b63252dbf6 | ||
|
|
5fb227b9f8 | ||
|
|
6ac866fdbf | ||
|
|
1452af3fc8 | ||
|
|
8e02810f0e | ||
|
|
74a64489e5 | ||
|
|
673074d618 | ||
|
|
1909786a4b | ||
|
|
4345c7bf2d | ||
|
|
03eff74d8b | ||
|
|
ee52959fab | ||
|
|
ab4c5b74c9 | ||
|
|
43221cbba6 | ||
|
|
be7f84adcf | ||
|
|
566a8e9ed2 | ||
|
|
2a9c7d9cfe | ||
|
|
d28a4af924 | ||
|
|
d973c83e01 | ||
|
|
1d1feee476 | ||
|
|
4bf94a7854 | ||
|
|
2cb254ef69 | ||
|
|
a9ebb102bd | ||
|
|
d9453835bf | ||
|
|
b0f614f82e | ||
|
|
709f2ae3dd | ||
|
|
0943797300 | ||
|
|
6f1fcbbf7a | ||
|
|
2a9e6af2ae | ||
|
|
ba3cda95e8 | ||
|
|
fbef175012 | ||
|
|
b94f25e5ae | ||
|
|
3b35751e2e | ||
|
|
dd37922fb2 | ||
|
|
1a153b31ee | ||
|
|
492c7290b0 | ||
|
|
d2322af34b | ||
|
|
a425afe9b6 | ||
|
|
081d88b9ad | ||
|
|
8ee0aea0b4 | ||
|
|
fcbdb77c79 | ||
|
|
e75ed159f6 | ||
|
|
632f24354b | ||
|
|
1e6da733a2 | ||
|
|
48b0c41f62 | ||
|
|
25d85f6759 | ||
|
|
2f83d488d6 | ||
|
|
871f1e0dfa | ||
|
|
752dbf6080 | ||
|
|
90deb5b1ff | ||
|
|
4cb535fcc9 | ||
|
|
97791544ab | ||
|
|
a6950408f2 | ||
|
|
3991fc5065 | ||
|
|
fc4b1bf7bb | ||
|
|
d13e340895 | ||
|
|
798661a0cf | ||
|
|
6aed5ab54f | ||
|
|
9cf55ed4ca | ||
|
|
65953d0d99 | ||
|
|
a060ae39b1 | ||
|
|
5d9a110d57 | ||
|
|
361fa2a7c3 | ||
|
|
703c8851b3 | ||
|
|
1d265c923e | ||
|
|
fad35aa4fa | ||
|
|
231ede1734 | ||
|
|
de8f9552c3 | ||
|
|
4c286ae6c1 | ||
|
|
767ae7bd07 | ||
|
|
cb7a79063e | ||
|
|
420e0319ca | ||
|
|
103070d00a | ||
|
|
6788fd1adf | ||
|
|
1485e8392e | ||
|
|
06ee94da03 | ||
|
|
cd9f7914e0 | ||
|
|
e57d97d3e6 | ||
|
|
b810fa7f4a | ||
|
|
8b0b833d6e | ||
|
|
869dbf6e10 | ||
|
|
1da6f37ec5 | ||
|
|
84e29bdf51 | ||
|
|
2864940a8e | ||
|
|
d25b883873 | ||
|
|
19697d5164 | ||
|
|
e02764bf4b | ||
|
|
d9b34fa631 | ||
|
|
1efc1337df | ||
|
|
c9eb6bcb38 | ||
|
|
350f3f375e | ||
|
|
140523dabb | ||
|
|
bee0bececf | ||
|
|
dcb42d43f1 | ||
|
|
5f1d57f987 | ||
|
|
8bca54ed7b | ||
|
|
075ca7521c | ||
|
|
9e803ffc19 | ||
|
|
bff56a2c61 | ||
|
|
b33e9de139 | ||
|
|
9ff35a69fe | ||
|
|
8a24fb113f | ||
|
|
db1b494d00 | ||
|
|
a6979298fd | ||
|
|
963d1c8eb2 | ||
|
|
b419b2e002 | ||
|
|
0586f306c0 | ||
|
|
7295492aa3 | ||
|
|
c842d36319 | ||
|
|
52ea229118 | ||
|
|
022db4956c | ||
|
|
45d270b03e | ||
|
|
c1a23b68ae | ||
|
|
a4b7707888 | ||
|
|
c3572d7c0c | ||
|
|
143990da34 | ||
|
|
6389ad49d5 | ||
|
|
9025ee3c24 | ||
|
|
1986ec6f0c | ||
|
|
ca2b6efd9b | ||
|
|
7867f84b87 | ||
|
|
0b9b8b8320 | ||
|
|
5859131678 | ||
|
|
c3f3bcb13f | ||
|
|
04e8b94b5d | ||
|
|
00e03c1d54 | ||
|
|
5920e06748 | ||
|
|
c6bfa2771b | ||
|
|
55cf5a9277 | ||
|
|
5eb7d4d1e6 | ||
|
|
e3e38fb6fa | ||
|
|
5ae6c8075b | ||
|
|
f48b0c17ed | ||
|
|
f9fba3227b | ||
|
|
0d404470c1 | ||
|
|
f079b5b43d | ||
|
|
a8a4f1671a | ||
|
|
a3367fc6ae | ||
|
|
94e06abbcb | ||
|
|
9edcc5110c | ||
|
|
bd261a32e9 | ||
|
|
9291fdcff6 | ||
|
|
a74ae41e3b | ||
|
|
ddc85a64f3 | ||
|
|
216bfa3326 | ||
|
|
c64797f2d9 | ||
|
|
aa48314ee9 | ||
|
|
011f6d161b | ||
|
|
dac467c1e6 | ||
|
|
889203c9de | ||
|
|
11fad87345 | ||
|
|
2e9f3d7726 | ||
|
|
f5a146255f | ||
|
|
22da88af7d | ||
|
|
4b997a4d0c | ||
|
|
ec5fa5f434 | ||
|
|
51e8e9e36a | ||
|
|
8e67897d7f | ||
|
|
ac28e5ef7a | ||
|
|
6698861c15 | ||
|
|
0ba85e2ee8 | ||
|
|
4e28b8faf9 | ||
|
|
ec37afc4d8 | ||
|
|
ffacd42baf | ||
|
|
1a707efeb8 | ||
|
|
fc1625a0ed | ||
|
|
f92085bb86 | ||
|
|
89dd225910 | ||
|
|
8f087e9ca1 | ||
|
|
dfeb0d709e | ||
|
|
a1f4e0342a | ||
|
|
64e511c3c5 | ||
|
|
70448dda08 | ||
|
|
c5498642fc | ||
|
|
925e83bbba | ||
|
|
a49a5d4cc2 | ||
|
|
6d606bbbd9 | ||
|
|
4d85236d16 | ||
|
|
b8a07e9648 |
57 changed files with 7839 additions and 2016 deletions
327
.golangci.yml
Normal file
327
.golangci.yml
Normal file
|
|
@ -0,0 +1,327 @@
|
|||
# This file contains all available configuration options
|
||||
# with their default values.
|
||||
|
||||
# options for analysis running
|
||||
run:
|
||||
# default concurrency is a available CPU number
|
||||
concurrency: 4
|
||||
|
||||
# timeout for analysis, e.g. 30s, 5m, default is 1m
|
||||
timeout: 1m
|
||||
|
||||
# exit code when at least one issue was found, default is 1
|
||||
issues-exit-code: 1
|
||||
|
||||
# include test files or not, default is true
|
||||
tests: true
|
||||
|
||||
# list of build tags, all linters use it. Default is empty list.
|
||||
build-tags:
|
||||
- mytag
|
||||
|
||||
# which dirs to skip: issues from them won't be reported;
|
||||
# can use regexp here: generated.*, regexp is applied on full path;
|
||||
# default value is empty list, but default dirs are skipped independently
|
||||
# from this option's value (see skip-dirs-use-default).
|
||||
skip-dirs:
|
||||
- src/external_libs
|
||||
- autogenerated_by_my_lib
|
||||
|
||||
# default is true. Enables skipping of directories:
|
||||
# vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
|
||||
skip-dirs-use-default: true
|
||||
|
||||
# which files to skip: they will be analyzed, but issues from them
|
||||
# won't be reported. Default value is empty list, but there is
|
||||
# no need to include all autogenerated files, we confidently recognize
|
||||
# autogenerated files. If it's not please let us know.
|
||||
skip-files:
|
||||
- ".*\\.my\\.go$"
|
||||
- lib/bad.go
|
||||
|
||||
# by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules":
|
||||
# If invoked with -mod=readonly, the go command is disallowed from the implicit
|
||||
# automatic updating of go.mod described above. Instead, it fails when any changes
|
||||
# to go.mod are needed. This setting is most useful to check that go.mod does
|
||||
# not need updates, such as in a continuous integration and testing system.
|
||||
# If invoked with -mod=vendor, the go command assumes that the vendor
|
||||
# directory holds the correct copies of dependencies and ignores
|
||||
# the dependency descriptions in go.mod.
|
||||
#! modules-download-mode: readonly|release|vendor
|
||||
|
||||
|
||||
# output configuration options
|
||||
output:
|
||||
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
|
||||
format: colored-line-number
|
||||
|
||||
# print lines of code with issue, default is true
|
||||
print-issued-lines: true
|
||||
|
||||
# print linter name in the end of issue text, default is true
|
||||
print-linter-name: true
|
||||
|
||||
# make issues output unique by line, default is true
|
||||
uniq-by-line: true
|
||||
|
||||
|
||||
# all available settings of specific linters
|
||||
linters-settings:
|
||||
dogsled:
|
||||
# checks assignments with too many blank identifiers; default is 2
|
||||
max-blank-identifiers: 2
|
||||
dupl:
|
||||
# tokens count to trigger issue, 150 by default
|
||||
threshold: 100
|
||||
errcheck:
|
||||
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
|
||||
# default is false: such cases aren't reported by default.
|
||||
check-type-assertions: false
|
||||
|
||||
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
|
||||
# default is false: such cases aren't reported by default.
|
||||
check-blank: false
|
||||
|
||||
# [deprecated] comma-separated list of pairs of the form pkg:regex
|
||||
# the regex is used to ignore names within pkg. (default "fmt:.*").
|
||||
# see https://github.com/kisielk/errcheck#the-deprecated-method for details
|
||||
ignore: fmt:.*,io/ioutil:^Read.*
|
||||
|
||||
# path to a file containing a list of functions to exclude from checking
|
||||
# see https://github.com/kisielk/errcheck#excluding-functions for details
|
||||
#!exclude: /path/to/file.txt
|
||||
funlen:
|
||||
lines: 60
|
||||
statements: 40
|
||||
gocognit:
|
||||
# minimal code complexity to report, 30 by default (but we recommend 10-20)
|
||||
min-complexity: 10
|
||||
goconst:
|
||||
# minimal length of string constant, 3 by default
|
||||
min-len: 3
|
||||
# minimal occurrences count to trigger, 3 by default
|
||||
min-occurrences: 3
|
||||
gocritic:
|
||||
# Which checks should be enabled; can't be combined with 'disabled-checks';
|
||||
# See https://go-critic.github.io/overview#checks-overview
|
||||
# To check which checks are enabled run `GL_DEBUG=gocritic golangci-lint run`
|
||||
# By default list of stable checks is used.
|
||||
enabled-checks:
|
||||
#!- rangeValCopy
|
||||
|
||||
# Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty
|
||||
disabled-checks:
|
||||
- regexpMust
|
||||
|
||||
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
|
||||
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
|
||||
enabled-tags:
|
||||
- performance
|
||||
|
||||
settings: # settings passed to gocritic
|
||||
captLocal: # must be valid enabled check name
|
||||
paramsOnly: true
|
||||
rangeValCopy:
|
||||
sizeThreshold: 32
|
||||
gocyclo:
|
||||
# minimal code complexity to report, 30 by default (but we recommend 10-20)
|
||||
min-complexity: 10
|
||||
godox:
|
||||
# report any comments starting with keywords, this is useful for TODO or FIXME comments that
|
||||
# might be left in the code accidentally and should be resolved before merging
|
||||
keywords: # default keywords are TODO, BUG, and FIXME, these can be overwritten by this setting
|
||||
- NOTE
|
||||
- OPTIMIZE # marks code that should be optimized before merging
|
||||
- HACK # marks hack-arounds that should be removed before merging
|
||||
gofmt:
|
||||
# simplify code: gofmt with `-s` option, true by default
|
||||
simplify: true
|
||||
goimports:
|
||||
# put imports beginning with prefix after 3rd-party packages;
|
||||
# it's a comma-separated list of prefixes
|
||||
local-prefixes: github.com/org/project
|
||||
golint:
|
||||
# minimal confidence for issues, default is 0.8
|
||||
min-confidence: 0.8
|
||||
gomnd:
|
||||
settings:
|
||||
mnd:
|
||||
# the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description.
|
||||
checks: argument,case,condition,operation,return,assign
|
||||
govet:
|
||||
# report about shadowed variables
|
||||
check-shadowing: true
|
||||
|
||||
# settings per analyzer
|
||||
settings:
|
||||
printf: # analyzer name, run `go tool vet help` to see all analyzers
|
||||
funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
|
||||
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
|
||||
|
||||
# enable or disable analyzers by name
|
||||
enable:
|
||||
- atomicalign
|
||||
enable-all: false
|
||||
disable:
|
||||
- shadow
|
||||
disable-all: false
|
||||
depguard:
|
||||
list-type: blacklist
|
||||
include-go-root: false
|
||||
packages:
|
||||
- github.com/sirupsen/logrus
|
||||
packages-with-error-message:
|
||||
# specify an error message to output when a blacklisted package is used
|
||||
- github.com/sirupsen/logrus: "logging is allowed only by logutils.Log"
|
||||
lll:
|
||||
# max line length, lines longer will be reported. Default is 120.
|
||||
# '\t' is counted as 1 character by default, and can be changed with the tab-width option
|
||||
line-length: 120
|
||||
# tab width in spaces. Default to 1.
|
||||
tab-width: 1
|
||||
maligned:
|
||||
# print struct with more effective memory layout or not, false by default
|
||||
suggest-new: true
|
||||
misspell:
|
||||
# Correct spellings using locale preferences for US or UK.
|
||||
# Default is to use a neutral variety of English.
|
||||
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
|
||||
locale: US
|
||||
ignore-words:
|
||||
- someword
|
||||
nakedret:
|
||||
# make an issue if func has more lines of code than this setting and it has naked returns; default is 30
|
||||
max-func-lines: 30
|
||||
prealloc:
|
||||
# XXX: we don't recommend using this linter before doing performance profiling.
|
||||
# For most programs usage of prealloc will be a premature optimization.
|
||||
|
||||
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
|
||||
# True by default.
|
||||
simple: true
|
||||
range-loops: true # Report preallocation suggestions on range loops, true by default
|
||||
for-loops: false # Report preallocation suggestions on for loops, false by default
|
||||
rowserrcheck:
|
||||
packages:
|
||||
- github.com/jmoiron/sqlx
|
||||
unparam:
|
||||
# Inspect exported functions, default is false. Set to true if no external program/library imports your code.
|
||||
# XXX: if you enable this setting, unparam will report a lot of false-positives in text editors:
|
||||
# if it's called for subdir of a project it can't find external interfaces. All text editor integrations
|
||||
# with golangci-lint call it on a directory with the changed file.
|
||||
check-exported: false
|
||||
unused:
|
||||
# treat code as a program (not a library) and report unused exported identifiers; default is false.
|
||||
# XXX: if you enable this setting, unused will report a lot of false-positives in text editors:
|
||||
# if it's called for subdir of a project it can't find funcs usages. All text editor integrations
|
||||
# with golangci-lint call it on a directory with the changed file.
|
||||
check-exported: false
|
||||
whitespace:
|
||||
multi-if: false # Enforces newlines (or comments) after every multi-line if statement
|
||||
multi-func: false # Enforces newlines (or comments) after every multi-line function signature
|
||||
wsl:
|
||||
# If true append is only allowed to be cuddled if appending value is
|
||||
# matching variables, fields or types on line above. Default is true.
|
||||
strict-append: true
|
||||
# Allow calls and assignments to be cuddled as long as the lines have any
|
||||
# matching variables, fields or types. Default is true.
|
||||
allow-assign-and-call: true
|
||||
# Allow multiline assignments to be cuddled. Default is true.
|
||||
allow-multiline-assign: true
|
||||
# Allow declarations (var) to be cuddled.
|
||||
allow-cuddle-declarations: false
|
||||
# Allow trailing comments in ending of blocks
|
||||
allow-trailing-comment: false
|
||||
# Force newlines in end of case at this limit (0 = never).
|
||||
force-case-trailing-whitespace: 0
|
||||
|
||||
# The custom section can be used to define linter plugins to be loaded at runtime. See README doc
|
||||
# for more info.
|
||||
custom:
|
||||
# Each custom linter should have a unique name.
|
||||
#! example:
|
||||
#! # The path to the plugin *.so. Can be absolute or local. Required for each custom linter
|
||||
#! path: /path/to/example.so
|
||||
#! # The description of the linter. Optional, just for documentation purposes.
|
||||
#! description: This is an example usage of a plugin linter.
|
||||
#! # Intended to point to the repo location of the linter. Optional, just for documentation purposes.
|
||||
#! original-url: github.com/golangci/example-linter
|
||||
|
||||
linters:
|
||||
enable:
|
||||
- megacheck
|
||||
- govet
|
||||
disable:
|
||||
- maligned
|
||||
- prealloc
|
||||
disable-all: false
|
||||
presets:
|
||||
- bugs
|
||||
- unused
|
||||
fast: false
|
||||
|
||||
|
||||
issues:
|
||||
# List of regexps of issue texts to exclude, empty list by default.
|
||||
# But independently from this option we use default exclude patterns,
|
||||
# it can be disabled by `exclude-use-default: false`. To list all
|
||||
# excluded by default patterns execute `golangci-lint run --help`
|
||||
exclude:
|
||||
- abcdef
|
||||
|
||||
# Excluding configuration per-path, per-linter, per-text and per-source
|
||||
exclude-rules:
|
||||
# Exclude some linters from running on tests files.
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- gocyclo
|
||||
- errcheck
|
||||
- dupl
|
||||
- gosec
|
||||
|
||||
# Exclude known linters from partially hard-vendored code,
|
||||
# which is impossible to exclude via "nolint" comments.
|
||||
- path: internal/hmac/
|
||||
text: "weak cryptographic primitive"
|
||||
linters:
|
||||
- gosec
|
||||
|
||||
# Exclude some staticcheck messages
|
||||
- linters:
|
||||
- staticcheck
|
||||
text: "SA9003:"
|
||||
|
||||
# Exclude lll issues for long lines with go:generate
|
||||
- linters:
|
||||
- lll
|
||||
source: "^//go:generate "
|
||||
|
||||
# Independently from option `exclude` we use default exclude patterns,
|
||||
# it can be disabled by this option. To list all
|
||||
# excluded by default patterns execute `golangci-lint run --help`.
|
||||
# Default value for this option is true.
|
||||
exclude-use-default: false
|
||||
|
||||
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
|
||||
max-issues-per-linter: 0
|
||||
|
||||
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
|
||||
max-same-issues: 0
|
||||
|
||||
# Show only new issues: if there are unstaged changes or untracked files,
|
||||
# only those changes are analyzed, else only changes in HEAD~ are analyzed.
|
||||
# It's a super-useful option for integration of golangci-lint into existing
|
||||
# large codebase. It's not practical to fix all existing issues at the moment
|
||||
# of integration: much better don't allow issues in new code.
|
||||
# Default is false.
|
||||
new: false
|
||||
|
||||
# Show only new issues created after git revision `REV`
|
||||
#!new-from-rev: REV
|
||||
#new-from-rev: HEAD^
|
||||
|
||||
# Show only new issues created in git patch with set file path.
|
||||
#!new-from-patch: path/to/patch/file
|
||||
61
CODE_OF_CONDUCT.md
Normal file
61
CODE_OF_CONDUCT.md
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
# Code of Merit (1.0-r1)
|
||||
|
||||
1. The project creators, lead developers, core team, ("The Maintainers") constitute
|
||||
the managing members of the project and have final say in every decision
|
||||
of the project, technical or otherwise, including overruling previous decisions.
|
||||
There are no limitations to this decisional power.
|
||||
|
||||
2. Contributions are an expected result of your membership on the project.
|
||||
Don't expect others to do your work or help you with your work forever.
|
||||
|
||||
3. All members have the same opportunities to seek any challenge they want
|
||||
within the project.
|
||||
|
||||
4. Authority or position in the project will be proportional
|
||||
to the accrued contribution. Seniority must be earned.
|
||||
|
||||
5. Software is evolutive: the better implementations must supersede lesser
|
||||
implementations. Technical advantage is the primary evaluation metric.
|
||||
|
||||
6. This is a space for technical prowess; topics outside of the project
|
||||
will not be tolerated.
|
||||
|
||||
7. Non technical conflicts will be discussed in a separate space. Disruption
|
||||
of the project will not be allowed.
|
||||
|
||||
8. Individual characteristics, including but not limited to,
|
||||
body, sex, sexual preference, race, language, religion, nationality,
|
||||
or political preferences are irrelevant in the scope of the project and
|
||||
will not be taken into account concerning your value or that of your contribution
|
||||
to the project.
|
||||
|
||||
9. Discuss or debate the idea, not the person.
|
||||
|
||||
10. There is no room for ambiguity: Ambiguity will be met with questioning;
|
||||
further ambiguity will be met with silence. It is the responsibility
|
||||
of the originator to provide requested context.
|
||||
|
||||
11. If something is illegal outside the scope of the project, it is illegal
|
||||
in the scope of the project. This Code of Merit does not take precedence over
|
||||
governing law within the jurisdiction(s) of The Maintainers.
|
||||
|
||||
(11.a) If the algorithms implemented in this project (eg., cryptography)
|
||||
are illegal or prohibited in your local jurisdiction, it is your personal
|
||||
responsibility to consider how, or if, you should attempt to participate in this
|
||||
project. The Maintainers disclaim all liability for others' actions and decisions
|
||||
in this regard.
|
||||
|
||||
12. This Code of Merit governs the technical procedures of the project not the
|
||||
activities outside of it.
|
||||
|
||||
13. Participation on the project equates to agreement of this Code of Merit.
|
||||
|
||||
14. No objectives beyond the stated objectives of this project are relevant
|
||||
to the project. Any intent to deviate the project from its original purpose
|
||||
of existence will constitute grounds for remedial action which may include
|
||||
expulsion from the project.
|
||||
|
||||
This document is based upon the original Code of Merit version 1.0 (Dec 4 2018).
|
||||
(https://web.archive.org/web/20181204203029/http://code-of-merit.org/)
|
||||
|
||||
Updated version (Mar 29 2020): https://codeofmerit.org/code/
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2017 - 2018 Omar Alejandro Herrera Reyna (core HerraduraKEx)
|
||||
Copyright (c) 2017 - 2018 Russell Magee (hkexsh/hkexshd/hkexpasswd)
|
||||
Copyright (c) 2017 - 2019 Russell Magee (xs/xsd/xsnet/xspasswd)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
674
LICENSE.gpl
674
LICENSE.gpl
|
|
@ -1,674 +0,0 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
118
Makefile
118
Makefile
|
|
@ -1,23 +1,115 @@
|
|||
.PHONY: clean lib client server passwd
|
||||
VERSION := 0.9.2
|
||||
.PHONY: lint vis clean common client server passwd subpkgs install uninstall reinstall
|
||||
|
||||
all: lib client server passwd
|
||||
## Tag version of binaries with build info wrt.
|
||||
## GO111MODULE(=on) and vendor/ setup vs. $GOPATH pkg builds
|
||||
############################################################
|
||||
ifeq ($(shell go env GOMOD),)
|
||||
MTAG=
|
||||
else
|
||||
MTAG="-m"
|
||||
endif
|
||||
|
||||
ifneq ($(VENDOR),)
|
||||
GOBUILDOPTS :=-v -mod vendor
|
||||
VTAG = "-v"
|
||||
else
|
||||
GOBUILDOPTS=
|
||||
VTAG =
|
||||
endif
|
||||
############################################################
|
||||
|
||||
GIT_COMMIT := $(shell git rev-list -1 HEAD)
|
||||
|
||||
#ifeq ($(BUILDOPTS),)
|
||||
BUILDOPTS :=$(BUILDOPTS)"$(GOBUILDOPTS) -ldflags \"-X main.version=$(VERSION)$(MTAG)$(VTAG) -X main.gitCommit=$(GIT_COMMIT)\""
|
||||
#endif
|
||||
|
||||
SUBPKGS = logger spinsult xsnet
|
||||
TOOLS = xs xsd
|
||||
SUBDIRS = $(LIBS) $(TOOLS)
|
||||
|
||||
ifeq ($(GOOS),)
|
||||
GOOS=$(shell go env GOOS)
|
||||
endif
|
||||
|
||||
ifeq ($(GOOS),windows)
|
||||
ifeq ($(MSYSTEM),MSYS)
|
||||
WIN_MSYS=1
|
||||
endif
|
||||
endif
|
||||
|
||||
|
||||
INSTPREFIX = /usr/local
|
||||
|
||||
all: common client server
|
||||
|
||||
clean:
|
||||
rm -f\
|
||||
hkexsh/hkexsh hkexsh/hkexsh.exe\
|
||||
hkexshd/hkexshd hkexshd/hkexshd.exe\
|
||||
hkexpasswd/hkexpasswd hkexpasswd/hkexpasswd.exe
|
||||
@echo "Make: $(MAKE)"
|
||||
go clean .
|
||||
for d in $(SUBDIRS); do\
|
||||
$(MAKE) -C $$d clean;\
|
||||
done
|
||||
|
||||
subpkgs:
|
||||
for d in $(SUBPKGS); do\
|
||||
$(MAKE) BUILDOPTS=$(BUILDOPTS) -C $$d all;\
|
||||
done
|
||||
|
||||
tools:
|
||||
for d in $(TOOLS); do\
|
||||
$(MAKE) BUILDOPTS=$(BUILDOPTS) -C $$d all;\
|
||||
done
|
||||
|
||||
|
||||
lib:
|
||||
common:
|
||||
go build .
|
||||
go install .
|
||||
|
||||
client: lib
|
||||
cd hkexsh; go build .; cd -
|
||||
|
||||
server: lib
|
||||
cd hkexshd; go build .; cd -
|
||||
client: common
|
||||
$(MAKE) BUILDOPTS=$(BUILDOPTS) -C xs
|
||||
|
||||
passwd: lib
|
||||
cd hkexpasswd; go build .; cd -
|
||||
|
||||
server: common
|
||||
ifeq ($(MSYSTEM),MSYS)
|
||||
echo "Build of xsd server for Windows not yet supported"
|
||||
else
|
||||
$(MAKE) BUILDOPTS=$(BUILDOPTS) -C xsd
|
||||
endif
|
||||
|
||||
vis:
|
||||
@which go-callvis >/dev/null 2>&1; \
|
||||
stat=$$?; if [ $$stat -ne "0" ]; then \
|
||||
/bin/echo "go-callvis not found. Run go get https://github.com/TrueFurby/go-callvis to install."; \
|
||||
else \
|
||||
$(MAKE) -C xs vis;\
|
||||
$(MAKE) -C xsd vis;\
|
||||
fi
|
||||
|
||||
lint:
|
||||
$(MAKE) -C xsd lint
|
||||
$(MAKE) -C xs lint
|
||||
|
||||
reinstall: uninstall install
|
||||
|
||||
install:
|
||||
echo "WIN_MSYS:" $(WIN_MSYS)
|
||||
ifdef WIN_MSYS
|
||||
cp xs/mintty_wrapper.sh $(INSTPREFIX)/bin/xs
|
||||
cp xs/mintty_wrapper.sh $(INSTPREFIX)/bin/xc
|
||||
cp xs/xs $(INSTPREFIX)/bin/_xs
|
||||
cp xs/xs $(INSTPREFIX)/bin/_xc
|
||||
echo "Install of xsd server for Windows not yet supported"
|
||||
else
|
||||
cp xs/xs $(INSTPREFIX)/bin
|
||||
cd $(INSTPREFIX)/bin && ln -s xs xc && cd -
|
||||
cp xsd/xsd $(INSTPREFIX)/sbin
|
||||
endif
|
||||
|
||||
uninstall:
|
||||
rm -f $(INSTPREFIX)/bin/xs $(INSTPREFIX)/bin/xc \
|
||||
$(INSTPREFIX)/bin/_xs $(INSTPREFIX)/bin/_xc
|
||||
ifndef $(WIN_MSYS)
|
||||
rm -f $(INSTPREFIX)/sbin/xsd
|
||||
endif
|
||||
|
|
|
|||
242
README.md
242
README.md
|
|
@ -1,68 +1,216 @@
|
|||
HKExSh
|
||||
[](https://godoc.org/blitter.com/go/xs)
|
||||
|
||||
# XS
|
||||
--
|
||||
|
||||
'hkexsh' (HerraduraKEx shell) is a golang implementation of a simple
|
||||
remote shell client and server, similar in role to ssh, offering
|
||||
encrypted interactive and non-interactive sessions. The client and server
|
||||
programs (hkexsh and hkexshd) use a mostly drop-in replacement for golang's
|
||||
standard golang/pkg/net facilities (net.Dial(), net.Listen(), net.Accept()
|
||||
XS (**X**perimental **S**hell) is a golang implementation of a simple remote shell client and
|
||||
server, similar in role to ssh, offering encrypted interactive and non-interactive sessions (remote commands),
|
||||
remote file copying and tunnels with optional traffic obfuscation ('chaffing').
|
||||
|
||||
It is stable to the point that I use it for day-to-day remote access in place of, and in preference to, ssh.
|
||||
|
||||
***
|
||||
**NOTE: Due to the experimental nature of the KEX/KEM algorithms used, and the novelty of the overall codebase, this package SHOULD BE CONSIDERED EXTREMELY EXPERIMENTAL and USED WITH CAUTION. It DEFINITELY SHOULD NOT be used for any sensitive applications. USE AT YOUR OWN RISK. NEITHER WARRANTY NOR CLAIM OF FITNESS FOR PURPOSE IS EXPRESSED OR IMPLIED.**
|
||||
|
||||
***
|
||||
|
||||
The client and server programs (xs and xsd) use a mostly drop-in
|
||||
replacement for golang's standard golang/pkg/net facilities (net.Dial(), net.Listen(), net.Accept()
|
||||
and the net.Conn type), which automatically negotiate keying material for
|
||||
'secure' sockets using the experimental HerraduraKEx key exchange algorithm
|
||||
first released at
|
||||
[Omar Elejandro Herrera Reyna's HerraduraKEx project](http://github.com/Caume/HerraduraKEx).
|
||||
secure sockets using one of a selectable set of experimental key exchange (KEX) or
|
||||
key encapsulation mechanisms (KEM).
|
||||
|
||||
One can simply replace calls to net.Dial() with hkex.Dial(), and likewise
|
||||
net.Listen() with hkex.Listen(), to obtain connections (hkex.Conn) conforming
|
||||
to the basic net.Conn interface. Upon Dial(), the HerraduraKEx key exchange
|
||||
is initiated (whereby client and server independently derive the same
|
||||
keying material).
|
||||
### Key Exchange
|
||||
Currently supported exchanges are:
|
||||
|
||||
Above the hkex.Conn layer, the server and client apps in this repository
|
||||
(server/hkexshd and client/hkexsh) negotiate session settings (cipher/hmac
|
||||
algorithms, interactive/non-interactive, etc.) to be used for further
|
||||
communication.
|
||||
* The HerraduraKEx key exchange algorithm first released at
|
||||
[Omar Elejandro Herrera Reyna's HerraduraKEx project](http://github.com/Caume/HerraduraKEx);
|
||||
* The KYBER IND-CCA-2 secure key encapsulation mechanism, [pq-crystals Kyber](https://pq-crystals.org/kyber/) :: [Yawning/kyber golang implementation](https://git.schwanenlied.me/yawning/kyber)
|
||||
* The NEWHOPE algorithm [newhopecrypto.org](https://www.newhopecrypto.org/) :: [Yawning/go-newhope golang implementation](https://git.schwanenlied.me/yawning/newhope)
|
||||
* The FrodoKEM algorithm [frodokem.org](https://frodokem.org/) :: Go version by [Eduardo E. S. Riccardi](https://github.com/kuking/go-frodokem)
|
||||
|
||||
NOTE: Due to the experimental nature of the HerraduraKEx algorithm used to
|
||||
derive crypto keying material, this algorithm and the demonstration remote
|
||||
shell client/server programs should be used with caution and should definitely
|
||||
NOT be used for any sensitive applications, or at the very least at one's
|
||||
own risk.
|
||||
Currently supported session algorithms:
|
||||
|
||||
As of this time (Jan 2018) no verdict by acknowledged 'crypto experts' as to
|
||||
[Encryption]
|
||||
* AES-256
|
||||
* Twofish-128
|
||||
* Blowfish-64
|
||||
* CryptMTv1 (64bit) (https://eprint.iacr.org/2005/165.pdf)
|
||||
* ChaCha20 (https://github.com/aead/chacha20)
|
||||
|
||||
[HMAC]
|
||||
* HMAC-SHA256
|
||||
* HMAC-SHA512
|
||||
|
||||
|
||||
### Conn
|
||||
Calls to xsnet.Dial() and xsnet.Listen()/Accept() are generally the same as calls to the equivalents within the _net_ package; however upon connection a key exchange automatically occurs whereby client and server independently derive the same keying material, and all following traffic is secured by a symmetric encryption algorithm.
|
||||
|
||||
### Session Negotiation
|
||||
Above the xsnet.Conn layer, the server and client apps in this repository (xsd/ and xs/ respectively) negotiate session settings (cipher/hmac algorithms, interactive/non-interactive mode, tunnel specifiers, etc.) to be used for communication.
|
||||
|
||||
### Padding and Chaffing
|
||||
Packets are subject to padding (random size, randomly applied as prefix or postfix), and optionally the client and server channels can both send _chaff_ packets at random defineable intervals to help thwart analysis of session activity (applicable to interactive and non-interactive command sessions, file copies and tunnels).
|
||||
|
||||
### Mux/Demux of Chaffing and Tunnel Data
|
||||
Chaffing and tunnels, if specified, are set up during initial client->server connection. Packets from the client local port(s) are sent through the main secured connection to the server's remote port(s), and vice versa, tagged with a chaff or tunnel specifier so that they can be discarded as chaff or de-multiplexed and delivered to the proper tunnel endpoints, respectively.
|
||||
|
||||
### Accounts and Passwords
|
||||
Within the ```xspasswd/``` directory is a password-setting utility, ```xspasswd```, used if one wishes ```xs``` access to use separate credentials from those of the default (likely ssh) login method. In this mode, ```xsd``` uses its own password file distinct from the system /etc/passwd to authenticate clients, using standard bcrypt+salt storage. Activate this mode by invoking ```xsd``` with ```-s false```.
|
||||
|
||||
HERRADURA KEX
|
||||
|
||||
As of this time (Oct 2018) no verdict by acknowledged 'crypto experts' as to
|
||||
the level of security of the HerraduraKEx algorithm for purposes of session
|
||||
key exchange over an insecure channel has been rendered.
|
||||
It is hoped that experts in the field will analyze the algorithm and
|
||||
determine if it is indeed a suitable one for use in situations where
|
||||
Diffie-Hellman or other key exchange algorithms are currently utilized.
|
||||
|
||||
Finally, within the hkexpasswd/ directory is a password-setting utility
|
||||
using its own user/password file distinct from the system /etc/passwd, which
|
||||
is used by the hkexshd server to authenticate clients.
|
||||
KYBER IND-CCA-2 KEM
|
||||
|
||||
Dependencies:
|
||||
--
|
||||
* Recent version of go (tested with go-1.9)
|
||||
As of this time (Oct 2018) Kyber is one of the candidate algorithms submitted to the [NIST post-quantum cryptography project](https://csrc.nist.gov/Projects/Post-Quantum-Cryptography). The authors recommend using it in "... so-called hybrid mode in combination with established "pre-quantum" security; for example in combination with elliptic-curve Diffie-Hellman." THIS PROJECT DOES NOT DO THIS (in case you didn't notice yet, THIS PROJECT IS EXPERIMENTAL.)
|
||||
|
||||
### Dependencies:
|
||||
|
||||
* Recent version of go (tested, at various times, with go-1.9 to go-1.12.4)
|
||||
* [github.com/mattn/go-isatty](http://github.com/mattn/go-isatty) //terminal tty detection
|
||||
* [github.com/kr/pty](http://github.com/kr/pty) //unix pty control (server pty connections)
|
||||
* [github.com/jameskeane/bcrypt](http://github.com/jameskeane/bcrypt) //password storage/auth
|
||||
* [blitter.com/go/goutmp](https://gogs.blitter.com/RLabs/goutmp) // wtmp/lastlog C bindings for user accounting
|
||||
* [https://git.schwanenlied.me/yawning/kyber](https://git.schwanenlied.me/yawning/kyber) // golang Kyber KEM
|
||||
* [https://git.schwanenlied.me/yawning/newhope](https://git.schwanenlied.me/yawning/newhope) // golang NEWHOPE,NEWHOPE-SIMPLE KEX
|
||||
* [blitter.com/go/mtwist](https://gogs.blitter.com/RLabs/mtwist) // 64-bit Mersenne Twister PRNG
|
||||
* [blitter.com/go/cryptmt](https://gogs.blitter.com/RLabs/cryptmt) // CryptMTv1 stream cipher
|
||||
|
||||
Get source code
|
||||
--
|
||||
* $ go get -u github.com/Russtopia/hkexsh
|
||||
* $ go get github.com/mattn/go-isatty ## only used by demos, not picked up by above go get -u?
|
||||
### Get source code
|
||||
|
||||
To build
|
||||
--
|
||||
* $ cd $GOPATH/src/github.com/Russtopia/hkexsh
|
||||
* $ make clean all
|
||||
```
|
||||
$ go get -u blitter.com/go/xs
|
||||
$ cd $GOPATH/src/blitter.com/go/xs
|
||||
$ go build ./... # install all dependent go pkgs
|
||||
```
|
||||
|
||||
To set accounts & passwords:
|
||||
--
|
||||
* $ sudo echo "joebloggs:*:*:*" >/etc/hkexsh.passwd
|
||||
* $ sudo hkexpasswd/hkexpasswd -u joebloggs
|
||||
* $ <enter a password, enter again to confirm>
|
||||
|
||||
Running Clent and Server. In separate shells:
|
||||
--
|
||||
* [A]$ sudo hkexshd/hkexshd &
|
||||
* [B]$ hkexsh/hkexsh -u joebloggs
|
||||
### To build
|
||||
|
||||
```
|
||||
$ cd $GOPATH/src/blitter.com/go/xs
|
||||
$ make clean all
|
||||
```
|
||||
|
||||
### To install, uninstall, re-install
|
||||
|
||||
```
|
||||
$ sudo make [install | uninstall | reinstall]
|
||||
```
|
||||
|
||||
### To manage service (openrc init)
|
||||
|
||||
An example init script (xsd.initrc) is provided. Consult your Linux distribution documentation for proper service/daemon installation. For openrc,
|
||||
|
||||
```
|
||||
$ sudo cp xsd.initrc /etc/init.d/xsd
|
||||
$ sudo rc-config add xsd default
|
||||
```
|
||||
|
||||
### To manage service (sysV init)
|
||||
|
||||
An example init script (xsd.sysvrc) is provided. Consult your Linux distribution documentation for proper service/daemon installation. For sysV init,
|
||||
|
||||
```
|
||||
$ sudo cp xsd.sysvrc /etc/init.d/xsd
|
||||
$ sudo sysv-rc-conf --level 2345 xsd on
|
||||
```
|
||||
|
||||
The make system assumes installation in /usr/local/sbin (xsd, xspasswd) and /usr/local/bin (xs/xc symlink).
|
||||
|
||||
```
|
||||
$ sudo rc-config [start | restart | stop] xsd
|
||||
```
|
||||
|
||||
### To set accounts & passwords:
|
||||
|
||||
```
|
||||
$ sudo touch /etc/xs.passwd
|
||||
$ sudo xspasswd/xspasswd -u joebloggs
|
||||
$ <enter a password, enter again to confirm>
|
||||
```
|
||||
|
||||
### Testing Client and Server from $GOPATH dev tree (w/o 'make install')
|
||||
|
||||
In separate shells A and B:
|
||||
```
|
||||
[A]$ cd xsd && sudo ./xsd & # add -d for debugging
|
||||
```
|
||||
|
||||
Interactive shell
|
||||
```
|
||||
[B]$ cd xs && ./xs joebloggs@host-or-ip # add -d for debugging
|
||||
```
|
||||
|
||||
One-shot command
|
||||
```
|
||||
[B]$ cd xs && ./xs -x "ls /tmp" joebloggs@host-or-ip
|
||||
```
|
||||
|
||||
WARNING WARNING WARNING: the -d debug flag will echo passwords to the log/console!
|
||||
Logging on Linux usually goes to /var/log/syslog and/or /var/log/debug, /var/log/daemon.log.
|
||||
|
||||
NOTE if running client (xs) with -d, one will likely need to run 'reset' afterwards
|
||||
to fix up the shell tty afterwards, as stty echo may not be restored if client crashes
|
||||
or is interrupted.
|
||||
|
||||
### Setting up an 'authtoken' for scripted (password-free) logins
|
||||
|
||||
Use the -g option of xs to request a token from the remote server, which will return a
|
||||
hostname:token string. Place this string into $HOME/.xs_id to allow logins without
|
||||
entering a password (obviously, $HOME/.xs_id on both server and client for the user
|
||||
should *not* be world-readable.)
|
||||
|
||||
### File Copying using xc
|
||||
|
||||
xc is a symlink to xs, and the binary checks its own filename to determine whether
|
||||
it is being invoked in 'shell' or 'copy' mode. Refer to the '-h' output for differences in
|
||||
accepted options.
|
||||
|
||||
General remote syntax is: user@server:[/]src-or-dest-path
|
||||
If no leading / is specified in src-or-dest-path, it is assumed to be relative to $HOME of the
|
||||
remote user. File operations are all performed as the remote user, so account permissions apply
|
||||
as expected.
|
||||
|
||||
Local (client) to remote (server) copy:
|
||||
```
|
||||
$ xc fileA /some/where/fileB /some/where/else/dirC joebloggs@host-or-ip:remoteDir
|
||||
```
|
||||
|
||||
Remote (server) to local (client) copy:
|
||||
```
|
||||
$ xc joebloggs@host-or-ip:/remoteDirOrFile /some/where/local/Dir
|
||||
```
|
||||
|
||||
xc uses a 'tarpipe' to send file data over the encrypted channel. Use the -d flag on client or server to see the generated tar commands if you're curious.
|
||||
|
||||
NOTE: Renaming while copying (eg., 'cp /foo/bar/fileA ./fileB') is NOT supported. Put another way, the destination (whether local or remote) must ALWAYS be a directory.
|
||||
|
||||
If the 'pv' pipeview utility is available (http://www.ivarch.com/programs/pv.shtml) file transfer progress and bandwidth control will be available (suppress the former with the -q option, set the latter with -L <bytes_per_second>).
|
||||
|
||||
### Tunnels
|
||||
|
||||
Simple tunnels (client -> server, no reverse tunnels for now) are supported.
|
||||
|
||||
Syntax: xs -T=<tunspec>{,<tunspec>...}
|
||||
.. where <tunspec> is <localport:remoteport>
|
||||
|
||||
Example, tunnelling ssh through xs
|
||||
|
||||
* [server side] ```$ sudo /usr/sbin/sshd -p 7002```
|
||||
* [client side, term A] ```$ xs -T=6002:7002 user@server```
|
||||
* [client side, term B] ```$ ssh user@localhost -p 6002```
|
||||
|
||||
|
||||
### Building for FreeBSD
|
||||
|
||||
The Makefile(s) to build require GNU make (gmake).
|
||||
Please install and invoke build via:
|
||||
```$ gmake clean all```
|
||||
|
|
|
|||
38
TODO.txt
Normal file
38
TODO.txt
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
HKExSh TODO Ideas
|
||||
--
|
||||
Chaff Improvements
|
||||
- Zipf or other distributions for chaff freq, packetsz
|
||||
- Mimicry of hand-typed traffic for chaff on interactive sessions
|
||||
- Client-input chaff file data (ie., Moby Dick)
|
||||
|
||||
KEx: Look at ECIES: https://godoc.org/github.com/bitherhq/go-bither/crypto/ecies
|
||||
ThreeBears? BIKE?, NTRU?: https://www.safecrypto.eu/pqclounge/
|
||||
NIST Round 1 submissions:
|
||||
https://csrc.nist.gov/projects/post-quantum-cryptography/round-1-submissions
|
||||
|
||||
|
||||
Architecture
|
||||
(DONE) - Move hkexnet components other than key exchange into a proper hkex package
|
||||
(ie., hkexsh imports hkex) - hkex should be usable for other client/svr utils,
|
||||
ala 'hkex-netcat')
|
||||
(parts split out into hkexnet/*, hkexsession.go)
|
||||
(DONE) - Make KEx fully-pluggable: isolate all code to do with Herradura into a
|
||||
KEx-neutral pkg so it can be swapped out for other methods (eg., DH etc.)
|
||||
(DONE - test branch) - Use system password db (/etc/{passwd,shadow})
|
||||
|
||||
Features
|
||||
(DONE) - Support for hkcp (hkex-cp) - secure file copy protocol
|
||||
(DONE) - auth tokens to allow scripted hkexsh/hkexcp use
|
||||
(DONE) - tunnelling - multiple tunnel sessions co-existing w/shell sessions
|
||||
- non-interactive tunnel-only mode
|
||||
- reverse tunnels
|
||||
|
||||
Alternate transports for hkexsh.Conn - HTTP-mimicking traffic, ICMP, ... ?
|
||||
(Whatever golang can support for net.Dial(), net.Accept(), io.Reader/Writer
|
||||
should in principle be usable as substrate for hkex.Conn)
|
||||
|
||||
Install
|
||||
(DONE - openrc) - init scripts for open-rc/init (and systemd, sigh)
|
||||
(DONE) - make install
|
||||
- common packages (yum/deb/portage)
|
||||
|
||||
227
auth.go
Executable file
227
auth.go
Executable file
|
|
@ -0,0 +1,227 @@
|
|||
package xs
|
||||
|
||||
// Package xs - a secure terminal client/server written from scratch in Go
|
||||
//
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
|
||||
// Authentication routines for the HKExSh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/user"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/jameskeane/bcrypt"
|
||||
passlib "gopkg.in/hlandau/passlib.v1"
|
||||
)
|
||||
|
||||
type AuthCtx struct {
|
||||
reader func(string) ([]byte, error) // eg. ioutil.ReadFile()
|
||||
userlookup func(string) (*user.User, error) // eg. os/user.Lookup()
|
||||
}
|
||||
|
||||
func NewAuthCtx( /*reader func(string) ([]byte, error), userlookup func(string) (*user.User, error)*/ ) (ret *AuthCtx) {
|
||||
ret = &AuthCtx{ioutil.ReadFile, user.Lookup}
|
||||
return
|
||||
}
|
||||
|
||||
// --------- System passwd/shadow auth routine(s) --------------
|
||||
|
||||
// VerifyPass verifies a password against system standard shadow file
|
||||
// Note auxilliary fields for expiry policy are *not* inspected.
|
||||
func VerifyPass(ctx *AuthCtx, user, password string) (bool, error) {
|
||||
if ctx.reader == nil {
|
||||
ctx.reader = ioutil.ReadFile // dependency injection hides that this is required
|
||||
}
|
||||
passlib.UseDefaults(passlib.Defaults20180601)
|
||||
var pwFileName string
|
||||
if runtime.GOOS == "linux" {
|
||||
pwFileName = "/etc/shadow"
|
||||
} else if runtime.GOOS == "freebsd" {
|
||||
pwFileName = "/etc/master.passwd"
|
||||
} else {
|
||||
pwFileName = "unsupported"
|
||||
}
|
||||
pwFileData, e := ctx.reader(pwFileName)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
pwLines := strings.Split(string(pwFileData), "\n")
|
||||
if len(pwLines) < 1 {
|
||||
return false, errors.New("Empty shadow file!")
|
||||
} else {
|
||||
var line string
|
||||
var hash string
|
||||
var idx int
|
||||
for idx = range pwLines {
|
||||
line = pwLines[idx]
|
||||
lFields := strings.Split(line, ":")
|
||||
if lFields[0] == user {
|
||||
hash = lFields[1]
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(hash) == 0 {
|
||||
return false, errors.New("nil hash!")
|
||||
} else {
|
||||
pe := passlib.VerifyNoUpgrade(password, hash)
|
||||
if pe != nil {
|
||||
return false, pe
|
||||
}
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// --------- End System passwd/shadow auth routine(s) ----------
|
||||
|
||||
// ------------- xs-local passwd auth routine(s) ---------------
|
||||
|
||||
// AuthUserByPasswd checks user login information using a password.
|
||||
// This checks /etc/xs.passwd for auth info, and system /etc/passwd
|
||||
// to cross-check the user actually exists.
|
||||
// nolint: gocyclo
|
||||
func AuthUserByPasswd(ctx *AuthCtx, username string, auth string, fname string) (valid bool, allowedCmds string) {
|
||||
if ctx.reader == nil {
|
||||
ctx.reader = ioutil.ReadFile // dependency injection hides that this is required
|
||||
}
|
||||
if ctx.userlookup == nil {
|
||||
ctx.userlookup = user.Lookup // again for dependency injection as dep is now hidden
|
||||
}
|
||||
b, e := ctx.reader(fname) // nolint: gosec
|
||||
if e != nil {
|
||||
valid = false
|
||||
log.Printf("ERROR: Cannot read %s!\n", fname)
|
||||
}
|
||||
r := csv.NewReader(bytes.NewReader(b))
|
||||
|
||||
r.Comma = ':'
|
||||
r.Comment = '#'
|
||||
r.FieldsPerRecord = 3 // username:salt:authCookie [TODO:disallowedCmdList (a,b,...)]
|
||||
for {
|
||||
record, err := r.Read()
|
||||
if err == io.EOF {
|
||||
// Use dummy entry if user not found
|
||||
// (prevent user enumeration attack via obvious timing diff;
|
||||
// ie., not attempting any auth at all)
|
||||
record = []string{"$nosuchuser$",
|
||||
"$2a$12$l0coBlRDNEJeQVl6GdEPbU",
|
||||
"$2a$12$l0coBlRDNEJeQVl6GdEPbUC/xmuOANvqgmrMVum6S4i.EXPgnTXy6"}
|
||||
username = "$nosuchuser$"
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if username == record[0] {
|
||||
tmp, err := bcrypt.Hash(auth, record[1])
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if tmp == record[2] && username != "$nosuchuser$" {
|
||||
valid = true
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
// Security scrub
|
||||
for i := range b {
|
||||
b[i] = 0
|
||||
}
|
||||
r = nil
|
||||
runtime.GC()
|
||||
|
||||
_, userErr := ctx.userlookup(username)
|
||||
if userErr != nil {
|
||||
valid = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ------------- End xs-local passwd auth routine(s) -----------
|
||||
|
||||
// AuthUserByToken checks user login information against an auth token.
|
||||
// Auth tokens are stored in each user's $HOME/.xs_id and are requested
|
||||
// via the -g option.
|
||||
// The function also check system /etc/passwd to cross-check the user
|
||||
// actually exists.
|
||||
func AuthUserByToken(ctx *AuthCtx, username string, connhostname string, auth string) (valid bool) {
|
||||
if ctx.reader == nil {
|
||||
ctx.reader = ioutil.ReadFile // dependency injection hides that this is required
|
||||
}
|
||||
if ctx.userlookup == nil {
|
||||
ctx.userlookup = user.Lookup // again for dependency injection as dep is now hidden
|
||||
}
|
||||
|
||||
auth = strings.TrimSpace(auth)
|
||||
u, ue := ctx.userlookup(username)
|
||||
if ue != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
b, e := ctx.reader(fmt.Sprintf("%s/.xs_id", u.HomeDir))
|
||||
if e != nil {
|
||||
log.Printf("INFO: Cannot read %s/.xs_id\n", u.HomeDir)
|
||||
return false
|
||||
}
|
||||
|
||||
r := csv.NewReader(bytes.NewReader(b))
|
||||
|
||||
r.Comma = ':'
|
||||
r.Comment = '#'
|
||||
r.FieldsPerRecord = 2 // connhost:authtoken
|
||||
for {
|
||||
record, err := r.Read()
|
||||
if err == io.EOF {
|
||||
return false
|
||||
}
|
||||
record[0] = strings.TrimSpace(record[0])
|
||||
record[1] = strings.TrimSpace(record[1])
|
||||
//fmt.Println("auth:", auth, "record:",
|
||||
// strings.Join([]string{record[0], record[1]}, ":"))
|
||||
|
||||
if (connhostname == record[0]) &&
|
||||
(auth == strings.Join([]string{record[0], record[1]}, ":")) {
|
||||
valid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
_, userErr := ctx.userlookup(username)
|
||||
if userErr != nil {
|
||||
valid = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func GetTool(tool string) (ret string) {
|
||||
ret = "/bin/"+tool
|
||||
_, err := os.Stat(ret)
|
||||
if err == nil {
|
||||
return ret
|
||||
}
|
||||
ret = "/usr/bin/"+tool
|
||||
_, err = os.Stat(ret)
|
||||
if err == nil {
|
||||
return ret
|
||||
}
|
||||
ret = "/usr/local/bin/"+tool
|
||||
_, err = os.Stat(ret)
|
||||
if err == nil {
|
||||
return ret
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
212
auth_test.go
Normal file
212
auth_test.go
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
package xs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/user"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type userVerifs struct {
|
||||
user string
|
||||
passwd string
|
||||
good bool
|
||||
}
|
||||
|
||||
var (
|
||||
dummyShadowA = `johndoe:$6$EeQlTtn/KXdSh6CW$UHbFuEw3UA0Jg9/GoPHxgWk6Ws31x3IjqsP22a9pVMOte0yQwX1.K34oI4FACu8GRg9DArJ5RyWUE9m98qwzZ1:18310:0:99999:7:::
|
||||
joebloggs:$6$F.0IXOrb0w0VJHG1$3O4PYyng7F3hlh42mbroEdQZvslybY5etPPiLMQJ1xosjABY.Q4xqAfyIfe03Du61ZjGQIt3nL0j12P9k1fsK/:18310:0:99999:7:::
|
||||
disableduser:!:18310::::::`
|
||||
|
||||
dummyAuthTokenFile = "hostA:abcdefg\nhostB:wxyz\n"
|
||||
|
||||
dummyXsPasswdFile = `#username:salt:authCookie
|
||||
bobdobbs:$2a$12$9vqGkFqikspe/2dTARqu1O:$2a$12$9vqGkFqikspe/2dTARqu1OuDKCQ/RYWsnaFjmi.HtmECRkxcZ.kBK
|
||||
notbob:$2a$12$cZpiYaq5U998cOkXzRKdyu:$2a$12$cZpiYaq5U998cOkXzRKdyuJ2FoEQyVLa3QkYdPQk74VXMoAzhvuP6
|
||||
`
|
||||
|
||||
testGoodUsers = []userVerifs{
|
||||
{"johndoe", "testpass", true},
|
||||
{"joebloggs", "testpass2", true},
|
||||
{"johndoe", "badpass", false},
|
||||
}
|
||||
|
||||
testXsPasswdUsers = []userVerifs{
|
||||
{"bobdobbs", "praisebob", true},
|
||||
{"notbob", "imposter", false},
|
||||
}
|
||||
|
||||
userlookup_arg_u string
|
||||
readfile_arg_f string
|
||||
)
|
||||
|
||||
func newMockAuthCtx(reader func(string) ([]byte, error), userlookup func(string) (*user.User, error)) (ret *AuthCtx) {
|
||||
ret = &AuthCtx{reader, userlookup}
|
||||
return
|
||||
}
|
||||
|
||||
func _mock_user_Lookup(username string) (*user.User, error) {
|
||||
username = userlookup_arg_u
|
||||
if username == "baduser" {
|
||||
return &user.User{}, errors.New("bad user")
|
||||
}
|
||||
urec := &user.User{Uid: "1000", Gid: "1000", Username: username, Name: "Full Name", HomeDir: "/home/user"}
|
||||
fmt.Printf(" [mock user rec:%v]\n", urec)
|
||||
return urec, nil
|
||||
}
|
||||
|
||||
func _mock_ioutil_ReadFile(f string) ([]byte, error) {
|
||||
f = readfile_arg_f
|
||||
if f == "/etc/shadow" {
|
||||
fmt.Println(" [mocking ReadFile(\"/etc/shadow\")]")
|
||||
return []byte(dummyShadowA), nil
|
||||
}
|
||||
if f == "/etc/xs.passwd" {
|
||||
fmt.Println(" [mocking ReadFile(\"/etc/xs.passwd\")]")
|
||||
return []byte(dummyXsPasswdFile), nil
|
||||
}
|
||||
if strings.Contains(f, "/.xs_id") {
|
||||
fmt.Println(" [mocking ReadFile(\".xs_id\")]")
|
||||
return []byte(dummyAuthTokenFile), nil
|
||||
}
|
||||
return []byte{}, errors.New("no readfile_arg_f supplied")
|
||||
}
|
||||
|
||||
func _mock_ioutil_ReadFileEmpty(f string) ([]byte, error) {
|
||||
return []byte{}, nil
|
||||
}
|
||||
|
||||
func _mock_ioutil_ReadFileHasError(f string) ([]byte, error) {
|
||||
return []byte{}, errors.New("IO Error")
|
||||
}
|
||||
|
||||
func TestVerifyPass(t *testing.T) {
|
||||
readfile_arg_f = "/etc/shadow"
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, nil)
|
||||
for idx, rec := range testGoodUsers {
|
||||
stat, e := VerifyPass(ctx, rec.user, rec.passwd)
|
||||
if rec.good && (!stat || e != nil) {
|
||||
t.Fatalf("failed %d\n", idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPassFailsOnEmptyFile(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFileEmpty, nil)
|
||||
stat, e := VerifyPass(ctx, "johndoe", "somepass")
|
||||
if stat || (e == nil) {
|
||||
t.Fatal("failed to fail w/empty file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPassFailsOnFileError(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFileEmpty, nil)
|
||||
stat, e := VerifyPass(ctx, "johndoe", "somepass")
|
||||
if stat || (e == nil) {
|
||||
t.Fatal("failed to fail on ioutil.ReadFile error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPassFailsOnDisabledEntry(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFileEmpty, nil)
|
||||
stat, e := VerifyPass(ctx, "disableduser", "!")
|
||||
if stat || (e == nil) {
|
||||
t.Fatal("failed to fail on disabled user entry")
|
||||
}
|
||||
}
|
||||
|
||||
////
|
||||
|
||||
func TestAuthUserByTokenFailsOnMissingEntryForHost(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
stat := AuthUserByToken(ctx, "johndoe", "hostZ", "abcdefg")
|
||||
if stat {
|
||||
t.Fatal("failed to fail on missing/mismatched host entry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByTokenFailsOnMissingEntryForUser(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
stat := AuthUserByToken(ctx, "unkuser", "hostA", "abcdefg")
|
||||
if stat {
|
||||
t.Fatal("failed to fail on wrong user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByTokenFailsOnUserLookupFailure(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
userlookup_arg_u = "baduser"
|
||||
stat := AuthUserByToken(ctx, "johndoe", "hostA", "abcdefg")
|
||||
if stat {
|
||||
t.Fatal("failed to fail with bad return from user.Lookup()")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByTokenFailsOnMismatchedTokenForUser(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
stat := AuthUserByToken(ctx, "johndoe", "hostA", "badtoken")
|
||||
if stat {
|
||||
t.Fatal("failed to fail with valid user, bad token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByTokenSucceedsWithMatchedUserAndToken(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
userlookup_arg_u = "johndoe"
|
||||
readfile_arg_f = "/.xs_id"
|
||||
stat := AuthUserByToken(ctx, userlookup_arg_u, "hostA", "hostA:abcdefg")
|
||||
if !stat {
|
||||
t.Fatal("failed with valid user and token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByPasswdFailsOnEmptyFile(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFileEmpty, _mock_user_Lookup)
|
||||
userlookup_arg_u = "bobdobbs"
|
||||
readfile_arg_f = "/etc/xs.passwd"
|
||||
stat, _ := AuthUserByPasswd(ctx, userlookup_arg_u, "praisebob", readfile_arg_f)
|
||||
if stat {
|
||||
t.Fatal("failed to fail with missing xs.passwd file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByPasswdFailsOnBadAuth(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
userlookup_arg_u = "bobdobbs"
|
||||
readfile_arg_f = "/etc/xs.passwd"
|
||||
stat, _ := AuthUserByPasswd(ctx, userlookup_arg_u, "wrongpass", readfile_arg_f)
|
||||
if stat {
|
||||
t.Fatal("failed to fail with valid user, incorrect passwd in xs.passwd file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByPasswdFailsOnBadUser(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
userlookup_arg_u = "bobdobbs"
|
||||
readfile_arg_f = "/etc/xs.passwd"
|
||||
stat, _ := AuthUserByPasswd(ctx, userlookup_arg_u, "theotherbob", readfile_arg_f)
|
||||
if stat {
|
||||
t.Fatal("failed to fail on invalid user vs. xs.passwd file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByPasswdPassesOnGoodAuth(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
userlookup_arg_u = "bobdobbs"
|
||||
readfile_arg_f = "/etc/xs.passwd"
|
||||
stat, _ := AuthUserByPasswd(ctx, userlookup_arg_u, "praisebob", readfile_arg_f)
|
||||
if !stat {
|
||||
t.Fatal("failed on valid user w/correct passwd in xs.passwd file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthUserByPasswdPassesOnOtherGoodAuth(t *testing.T) {
|
||||
ctx := newMockAuthCtx(_mock_ioutil_ReadFile, _mock_user_Lookup)
|
||||
userlookup_arg_u = "notbob"
|
||||
readfile_arg_f = "/etc/xs.passwd"
|
||||
stat, _ := AuthUserByPasswd(ctx, userlookup_arg_u, "imposter", readfile_arg_f)
|
||||
if !stat {
|
||||
t.Fatal("failed on valid user 2nd entry w/correct passwd in xs.passwd file")
|
||||
}
|
||||
}
|
||||
105
bacillus/ci_pushbuild.sh
Executable file
105
bacillus/ci_pushbuild.sh
Executable file
|
|
@ -0,0 +1,105 @@
|
|||
#!/bin/bash
|
||||
#
|
||||
## bacillus (https://gogs.blitter.com/Russtopia/bacillus) build/test CI script
|
||||
|
||||
export GOPATH="${HOME}/go"
|
||||
export PATH=/usr/local/bin:/usr/bin:/usr/lib/ccache/bin:/bin:$GOPATH/bin
|
||||
export GO111MODULE=on
|
||||
# GOCACHE will be phased out in v1.12. [github.com/golang/go/issues/26809]
|
||||
export GOCACHE="${HOME}/.cache/go-build"
|
||||
|
||||
echo "workdir: ${BACILLUS_WORKDIR}"
|
||||
mkdir -p "${BACILLUS_ARTFDIR}"
|
||||
|
||||
echo "---"
|
||||
go env
|
||||
echo "---"
|
||||
echo "passed env:"
|
||||
env
|
||||
echo "---"
|
||||
|
||||
cd ${REPO}
|
||||
branch=$(git for-each-ref --sort=-committerdate --format='%(refname)' | head -n 1)
|
||||
echo "Building most recent push on branch $branch"
|
||||
git checkout "$branch"
|
||||
ls
|
||||
|
||||
############
|
||||
stage "Build"
|
||||
############
|
||||
make all
|
||||
|
||||
############
|
||||
stage "UnitTests"
|
||||
############
|
||||
go test -v .
|
||||
|
||||
############
|
||||
stage "Test(Authtoken)"
|
||||
############
|
||||
if [ -f ~/.xs_id ]; then
|
||||
echo "Clearing test user $USER ~/.xs_id file ..."
|
||||
mv ~/.xs_id ~/.xs_id.bak
|
||||
fi
|
||||
echo "Setting dummy authtoken in ~/.xs_id ..."
|
||||
echo "localhost:asdfasdfasdf" >~/.xs_id
|
||||
echo "Performing remote command on @localhost via authtoken login ..."
|
||||
tokentest=$(timeout 10 xs -x "echo -n FOO" @localhost)
|
||||
if [ "${tokentest}" != "FOO" ]; then
|
||||
echo "AUTHTOKEN LOGIN FAILED"
|
||||
exit 1
|
||||
else
|
||||
echo "client cmd performed OK."
|
||||
unset tokentest
|
||||
fi
|
||||
|
||||
############
|
||||
stage "Test(S->C)"
|
||||
############
|
||||
echo "Testing secure copy from server -> client ..."
|
||||
tmpdir=$$
|
||||
mkdir -p /tmp/$tmpdir
|
||||
cd /tmp/$tmpdir
|
||||
xc @localhost:${BACILLUS_WORKDIR}/build/xs/cptest .
|
||||
echo -n "Integrity check on copied files (sha1sum) ..."
|
||||
sha1sum $(find cptest -type f | sort) >sc.sha1sum
|
||||
diff sc.sha1sum ${BACILLUS_WORKDIR}/build/xs/cptest.sha1sum
|
||||
stat=$?
|
||||
cd -
|
||||
|
||||
rm -rf /tmp/$tmpdir
|
||||
if [ $stat -eq "0" ]; then
|
||||
echo "OK."
|
||||
else
|
||||
echo "FAILED!"
|
||||
exit $stat
|
||||
fi
|
||||
|
||||
############
|
||||
stage "Test(C->S)"
|
||||
############
|
||||
echo "TODO ..."
|
||||
|
||||
if [ -f ~/.xs_id.bak ]; then
|
||||
echo "Restoring test user $USER ~/.xs_id file ..."
|
||||
mv ~/.xs_id.bak ~/.xs_id
|
||||
fi
|
||||
|
||||
############
|
||||
stage "Lint"
|
||||
############
|
||||
make lint
|
||||
|
||||
############
|
||||
stage "Artifacts"
|
||||
############
|
||||
echo -n "Creating tarfile ..."
|
||||
tar -cz --exclude=.git --exclude=cptest -f ${BACILLUS_ARTFDIR}/xs.tgz .
|
||||
|
||||
############
|
||||
stage "Cleanup"
|
||||
############
|
||||
# nop
|
||||
|
||||
echo
|
||||
echo "--Done--"
|
||||
10
consts.go
Normal file
10
consts.go
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
// Package xs - a secure terminal client/server written from scratch in Go
|
||||
//
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
package xs
|
||||
|
||||
// common constants for the XS (Xperimental Shell)
|
||||
12
cp.cmd
Normal file
12
cp.cmd
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
## Template for copying files from local to remote site, destdir DEST:
|
||||
tar -cz -f - testdir/sub1/bar.txt | \
|
||||
tar -xzv -C DEST --xform="s#.*/\(.*\)#\1#"
|
||||
|
||||
# Note the --xform= option will strip leading path components from the file
|
||||
# on extraction (ie., throw away dirtree info when copying into remote DEST)
|
||||
#
|
||||
# Probably need to have a '-r' option ala 'scp -r' to control --xform=
|
||||
# (in the absence of --xform=.. above, files and dirs will all be extracted
|
||||
# to remote DEST preserving tree structure.)
|
||||
|
||||
tar cf /dev/stdout ../*.txt | tar xf -
|
||||
6
cptest.sha1sum
Normal file
6
cptest.sha1sum
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
306637b5c621892078ebadd9454a78820a000598 cptest/file16KB
|
||||
1a118dfff291352eb4aec02c34f4f957669460fc cptest/file1KB
|
||||
f474d5da45890b7cb5b0ae84c8ade5abcb3b4474 cptest/file32KB
|
||||
03939175ceac92b9c6464d037a0243e22563c423 cptest/file6B
|
||||
da67c7698b25d94c0cc20284ba9d4008cdee201b cptest/subdir/file32MB
|
||||
9da9888265371375b48c224b94a0b3132b7ddc41 cptest/subdir/file64MB
|
||||
9
fixup-gv.sh
Executable file
9
fixup-gv.sh
Executable file
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/bash
|
||||
|
||||
inFile="${1/.go/}"
|
||||
visFile="${inFile}-vis.gv"
|
||||
|
||||
#grep -o "\.[a-zA-Z_]*\$[0-9]*" "$inFile"-vis.gv | sort | uniq
|
||||
grep -o "#gv:.*" "$inFile.go" | cut -f2 -d: | \
|
||||
while read -r expr; do sed -i ${expr} "${visFile}"; done
|
||||
|
||||
30
go.mod
Normal file
30
go.mod
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
module blitter.com/go/xs
|
||||
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
blitter.com/go/cryptmt v1.0.2
|
||||
blitter.com/go/goutmp v1.0.5
|
||||
blitter.com/go/herradurakex v1.0.0
|
||||
blitter.com/go/kyber v0.0.0-20200130200857-6f2021cb88d9
|
||||
blitter.com/go/mtwist v1.0.1 // indirect
|
||||
blitter.com/go/newhope v0.0.0-20200130200750-192fc08a8aae
|
||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da
|
||||
github.com/creack/pty v1.1.11
|
||||
github.com/jameskeane/bcrypt v0.0.0-20120420032655-c3cd44c1e20f
|
||||
github.com/klauspost/reedsolomon v1.9.9 // indirect
|
||||
github.com/kuking/go-frodokem v1.0.1
|
||||
github.com/mattn/go-isatty v0.0.12
|
||||
github.com/mmcloughlin/avo v0.0.0-20200523190732-4439b6b2c061 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 // indirect
|
||||
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b // indirect
|
||||
github.com/tjfoc/gmsm v1.3.1 // indirect
|
||||
github.com/xtaci/kcp-go v5.4.20+incompatible
|
||||
github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37 // indirect
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37
|
||||
golang.org/x/sys v0.0.0-20200523222454-059865788121
|
||||
gopkg.in/hlandau/easymetric.v1 v1.0.0 // indirect
|
||||
gopkg.in/hlandau/measurable.v1 v1.0.1 // indirect
|
||||
gopkg.in/hlandau/passlib.v1 v1.0.10
|
||||
)
|
||||
94
go.sum
Normal file
94
go.sum
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
blitter.com/go/chacha20 v0.0.0-20200130200441-214e4085f54c h1:LcnFFg6MCIJHf26P7eOUST45fNLHJI5erq0gWZaDLCo=
|
||||
blitter.com/go/chacha20 v0.0.0-20200130200441-214e4085f54c/go.mod h1:EMJtRcf22WCtHGiXCw+NB/Sb/PYcXtUgUql6LDEwyXo=
|
||||
blitter.com/go/cryptmt v1.0.2 h1:ZcLhQk7onUssXyQwG3GdXDXctCVnNL+b7aFuvwOdKXc=
|
||||
blitter.com/go/cryptmt v1.0.2/go.mod h1:tdME2J3O4agaDAYIYNQzzuB28yVGnPSMmV3a/ucSU84=
|
||||
blitter.com/go/goutmp v1.0.5 h1:isP6bxSs1O06Oy7wB8u4y5SgLr22txfjg/gjG4qn0Og=
|
||||
blitter.com/go/goutmp v1.0.5/go.mod h1:gtlbjC8xGzMk/Cf0BpnVltSa3awOqJ+B5WAxVptTMxk=
|
||||
blitter.com/go/herradurakex v1.0.0 h1:6XaxY+JLT1HUWPF0gYJnjX3pVjrw4YhYZEzZ1U0wkyc=
|
||||
blitter.com/go/herradurakex v1.0.0/go.mod h1:m3+vYZX+2dDjdo+n/HDnXEYJX9pwmNeQLgAfJM8mtxw=
|
||||
blitter.com/go/kyber v0.0.0-20200130200857-6f2021cb88d9 h1:D45AnrNphtvczBXRp5JQicZRTgaK/Is5bgPDDvRKhTc=
|
||||
blitter.com/go/kyber v0.0.0-20200130200857-6f2021cb88d9/go.mod h1:SK6QfGG72lIfKW1Td0wH7f0wwN5nSIhV3K+wvzGNjrw=
|
||||
blitter.com/go/mtwist v1.0.1 h1:PxmoWexfMpLmc8neHP/PcRc3s17ct7iz4d5W/qJVt04=
|
||||
blitter.com/go/mtwist v1.0.1/go.mod h1:aU82Nx8+b1v8oZRNqImfEDzDTPim81rY0ACKAIclV18=
|
||||
blitter.com/go/newhope v0.0.0-20200130200750-192fc08a8aae h1:YBBaCcdYRrI1btsmcMTv1VMPmaSXXz0RwKOTgMJYSRU=
|
||||
blitter.com/go/newhope v0.0.0-20200130200750-192fc08a8aae/go.mod h1:ywoxfDBqInPsqtnxYsmS4SYMJ5D/kNcrFgpvI+Xcun0=
|
||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY=
|
||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA=
|
||||
github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
|
||||
github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/jameskeane/bcrypt v0.0.0-20120420032655-c3cd44c1e20f h1:UWGE8Vi+1Agt0lrvnd7UsmvwqWKRzb9byK9iQmsbY0Y=
|
||||
github.com/jameskeane/bcrypt v0.0.0-20120420032655-c3cd44c1e20f/go.mod h1:u+9Snq0w+ZdYKi8BBoaxnEwWu0fY4Kvu9ByFpM51t1s=
|
||||
github.com/klauspost/cpuid v1.2.4 h1:EBfaK0SWSwk+fgk6efYFWdzl8MwRWoOO1gkmiaTXPW4=
|
||||
github.com/klauspost/cpuid v1.2.4/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
|
||||
github.com/klauspost/reedsolomon v1.9.9 h1:qCL7LZlv17xMixl55nq2/Oa1Y86nfO8EqDfv2GHND54=
|
||||
github.com/klauspost/reedsolomon v1.9.9/go.mod h1:O7yFFHiQwDR6b2t63KPUpccPtNdp5ADgh1gg4fd12wo=
|
||||
github.com/kuking/go-frodokem v1.0.1 h1:13bks3u4CPpvUtOLttT+A37j9myV4kLnS7Z3qDiTm4o=
|
||||
github.com/kuking/go-frodokem v1.0.1/go.mod h1:TzD0W9QnVOcwigeSySEuNZfJaGxWRtFRb7hXe/w/waI=
|
||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mmcloughlin/avo v0.0.0-20200523190732-4439b6b2c061 h1:UCU8+cLbbvyxi0sQ9fSeoEhZgvrrD9HKMtX6Gmc1vk8=
|
||||
github.com/mmcloughlin/avo v0.0.0-20200523190732-4439b6b2c061/go.mod h1:wqKykBG2QzQDJEzvRkcS8x6MiSJkF52hXZsXcjaB3ls=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 h1:89CEmDvlq/F7SJEOqkIdNDGJXrQIhuIx9D2DBXjavSU=
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU=
|
||||
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b h1:fj5tQ8acgNUr6O8LEplsxDhUIe2573iLkJc+PqnzZTI=
|
||||
github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4=
|
||||
github.com/tjfoc/gmsm v1.3.1 h1:+k3IAlF81c31/TllJmIfuCYnjl8ziMdTWGWJcP9J1uo=
|
||||
github.com/tjfoc/gmsm v1.3.1/go.mod h1:HaUcFuY0auTiaHB9MHFGCPx5IaLhTUd2atbCFBQXn9w=
|
||||
github.com/ulikunitz/xz v0.5.7 h1:YvTNdFzX6+W5m9msiYg/zpkSURPPtOlzbqYjrFn7Yt4=
|
||||
github.com/ulikunitz/xz v0.5.7/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/xtaci/kcp-go v5.4.20+incompatible h1:TN1uey3Raw0sTz0Fg8GkfM0uH3YwzhnZWQ1bABv5xAg=
|
||||
github.com/xtaci/kcp-go v5.4.20+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45a+AZwO7eyRCmEIbtvE=
|
||||
github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37 h1:EWU6Pktpas0n8lLQwDsRyZfmkPeRbdgPtW609es+/9E=
|
||||
github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37/go.mod h1:HpMP7DB2CyokmAh4lp0EQnnWhmycP/TvwBGzvuie+H0=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
golang.org/x/arch v0.0.0-20190909030613-46d78d1859ac/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190829043050-9756ffdc2472/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20191219195013-becbf705a915/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200128174031-69ecbb4d6d5d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b h1:0mm1VjtFUOIlE1SbDlwjYaDxZVDP2S5ou6y0gSgXHu8=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190902133755-9109b7679e13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o=
|
||||
golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200425043458-8463f397d07c h1:iHhCR0b26amDCiiO+kBguKZom9aMF+NrFxh9zeKR/XU=
|
||||
golang.org/x/tools v0.0.0-20200425043458-8463f397d07c/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/hlandau/easymetric.v1 v1.0.0 h1:ZbfbH7W3giuVDjWUoFhDOjjv20hiPr5HZ2yMV5f9IeE=
|
||||
gopkg.in/hlandau/easymetric.v1 v1.0.0/go.mod h1:yh75hypuFzAxmvECh3ZKGCvFnIfapYJh2wv7ASaX2RE=
|
||||
gopkg.in/hlandau/measurable.v1 v1.0.1 h1:wH5UZKCRUnRr1iD+xIZfwhtxhmr+bprRJttqA1Rklf4=
|
||||
gopkg.in/hlandau/measurable.v1 v1.0.1/go.mod h1:6N+SYJGMTmetsx7wskULP+juuO+++tsHJkAgzvzsbuM=
|
||||
gopkg.in/hlandau/passlib.v1 v1.0.10 h1:q5xh9ZHp907XTjVw8/EqG03//fnlITnIYQmv4Gn7TpE=
|
||||
gopkg.in/hlandau/passlib.v1 v1.0.10/go.mod h1:wxGAv2CtQHlzWY8NJp+p045yl4WHyX7v2T6XbOcmqjM=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
44
grml.yaml
Normal file
44
grml.yaml
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
env:
|
||||
project: xs
|
||||
version: 0.8.0
|
||||
buildDir: build/
|
||||
docDir: doc/
|
||||
releaseDir: ${project}-${version}/
|
||||
|
||||
options:
|
||||
debug: false
|
||||
breakfast:
|
||||
- sausage & spam
|
||||
- spam, egg, sausage & spam
|
||||
- spam, spam, beans, spam & spam
|
||||
|
||||
commands:
|
||||
release:
|
||||
help: do full rebuild, docgen and store artifacts in ${releaseDir}
|
||||
deps:
|
||||
- vis
|
||||
- app
|
||||
exec: |
|
||||
echo "TODO: cp binary and docs to ${releaseDir}"
|
||||
|
||||
install:
|
||||
help: install binaries (root)
|
||||
deps:
|
||||
- app
|
||||
as-root: true
|
||||
exec: |
|
||||
make reinstall
|
||||
|
||||
vis:
|
||||
help: generate graphviz (via go-callvis)
|
||||
deps:
|
||||
- app
|
||||
exec: |
|
||||
make vis
|
||||
|
||||
app:
|
||||
aliases: [ build ]
|
||||
help: build the xs tools
|
||||
exec: |
|
||||
make clean
|
||||
make all
|
||||
169
herradurakex.go
169
herradurakex.go
|
|
@ -1,169 +0,0 @@
|
|||
// Package hkexsh - socket lib conforming to
|
||||
// golang.org/pkg/net Conn interface, with
|
||||
// experimental key exchange algorithm by
|
||||
// Omar Alejandro Herrera Reyna.
|
||||
//
|
||||
// (https://github.com/Caume/HerraduraKEx)
|
||||
//
|
||||
// The core HerraduraKEx algorithm is dual-licensed
|
||||
// by the author (Omar Alejandro Herrera Reyna)
|
||||
// under GPL3 and MIT licenses.
|
||||
// See LICENSE.gpl and LICENSE.mit in this distribution
|
||||
//
|
||||
// Copyright (c) 2017-2018 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
package hkexsh
|
||||
|
||||
/* Herradura - a Key exchange scheme in the style of Diffie-Hellman Key Exchange.
|
||||
Copyright (C) 2017 Omar Alejandro Herrera Reyna
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
golang implementation by Russ Magee (rmagee_at_gmail.com) */
|
||||
|
||||
/* This is the core KEx algorithm. For client/server net support code,
|
||||
See hkexnet.go for a golang/pkg/net for the compatible Conn interface
|
||||
using this to transparently negotiate keys and secure a network channel. */
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HerraduraKEx holds the session state for a key exchange.
|
||||
type HerraduraKEx struct {
|
||||
intSz, pubSz int
|
||||
randctx *rand.Rand
|
||||
a *big.Int
|
||||
b *big.Int
|
||||
d, PeerD *big.Int
|
||||
fa *big.Int
|
||||
}
|
||||
|
||||
// New returns a HerraduraKEx struct.
|
||||
//
|
||||
// i - internal (private) random nonce
|
||||
// p - public (exchanged) random nonce (typically 1/4 bitsize of i)
|
||||
//
|
||||
// If i or p are passed as zero, they will default to 256 and 64,
|
||||
// respectively.
|
||||
func New(i int, p int) (h *HerraduraKEx) {
|
||||
h = new(HerraduraKEx)
|
||||
|
||||
if i == 0 {
|
||||
i = 256
|
||||
}
|
||||
if p == 0 {
|
||||
p = 64
|
||||
}
|
||||
|
||||
h.intSz = i
|
||||
h.pubSz = p
|
||||
|
||||
h.seed()
|
||||
h.a = h.rand()
|
||||
h.b = h.rand()
|
||||
|
||||
h.d = h.fscxRevolve(h.a, h.b, h.pubSz)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *HerraduraKEx) seed() {
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
h.randctx = r
|
||||
}
|
||||
|
||||
func (h *HerraduraKEx) rand() (v *big.Int) {
|
||||
v = big.NewInt(0)
|
||||
v.Rand(h.randctx, h.getMax())
|
||||
return v
|
||||
}
|
||||
|
||||
// getMax returns the max value for an n-bit big.Int
|
||||
func (h *HerraduraKEx) getMax() (n *big.Int) {
|
||||
n = big.NewInt(0)
|
||||
var max big.Int
|
||||
|
||||
for i := 0; i < h.intSz; i++ {
|
||||
max.SetBit(n, i, 1)
|
||||
}
|
||||
n = &max
|
||||
return n
|
||||
}
|
||||
|
||||
func (h *HerraduraKEx) bitX(x *big.Int, pos int) (ret int64) {
|
||||
if pos < 0 {
|
||||
pos = h.intSz - pos
|
||||
}
|
||||
|
||||
if pos == 0 {
|
||||
ret = int64(x.Bit(1) ^ x.Bit(0) ^ x.Bit(h.intSz-1))
|
||||
} else if pos == h.intSz-1 {
|
||||
ret = int64(x.Bit(0) ^ x.Bit(pos) ^ x.Bit(pos-1))
|
||||
} else {
|
||||
ret = int64(x.Bit((pos+1)%h.intSz) ^ x.Bit(pos) ^ x.Bit(pos-1))
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func (h *HerraduraKEx) bit(up, down *big.Int, posU, posD int) (ret *big.Int) {
|
||||
return big.NewInt(h.bitX(up, posU) ^ h.bitX(down, posD))
|
||||
}
|
||||
|
||||
func (h *HerraduraKEx) fscx(up, down *big.Int) (result *big.Int) {
|
||||
result = big.NewInt(0)
|
||||
|
||||
for count := 0; count < h.intSz; count++ {
|
||||
result.Lsh(result, 1)
|
||||
result.Add(result, h.bit(up, down, count, count))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// This is the iteration function using the result of the previous iteration
|
||||
// as the first parameter and the second parameter of the first iteration.
|
||||
func (h *HerraduraKEx) fscxRevolve(x, y *big.Int, passes int) (result *big.Int) {
|
||||
result = x
|
||||
for count := 0; count < passes; count++ {
|
||||
result = h.fscx(result, y)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// D returns the D (FSCX Revolved) value, input to generate FA
|
||||
// (the value for peer KEx)
|
||||
func (h *HerraduraKEx) D() *big.Int {
|
||||
return h.d
|
||||
}
|
||||
|
||||
// FA returns the FA value, which must be sent to peer for KEx.
|
||||
func (h *HerraduraKEx) FA() {
|
||||
h.fa = h.fscxRevolve(h.PeerD, h.b, h.intSz-h.pubSz)
|
||||
h.fa.Xor(h.fa, h.a)
|
||||
}
|
||||
|
||||
// Output HerraduraKEx type value as a string. Implements Stringer interface.
|
||||
func (h *HerraduraKEx) String() string {
|
||||
return fmt.Sprintf("s:%d p:%d\na:%s\nb:%s\nd:->%s\n<-PeerD:%s\nfa:%s",
|
||||
h.intSz, h.pubSz,
|
||||
h.a.Text(16), h.b.Text(16),
|
||||
h.d.Text(16),
|
||||
h.PeerD.Text(16),
|
||||
h.fa.Text(16))
|
||||
}
|
||||
55
hkexauth.go
55
hkexauth.go
|
|
@ -1,55 +0,0 @@
|
|||
// Authentication routines for the HKExSh
|
||||
//
|
||||
// Copyright (c) 2017-2018 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
|
||||
package hkexsh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"runtime"
|
||||
|
||||
"github.com/jameskeane/bcrypt"
|
||||
)
|
||||
|
||||
func AuthUser(username string, auth string, fname string) (valid bool, allowedCmds string) {
|
||||
b, e := ioutil.ReadFile(fname)
|
||||
if e != nil {
|
||||
valid = false
|
||||
log.Println("ERROR: Cannot read hkexsh.passwd file!")
|
||||
log.Fatal(e)
|
||||
}
|
||||
r := csv.NewReader(bytes.NewReader(b))
|
||||
|
||||
b = nil
|
||||
runtime.GC() // Paranoia and prob. not effective; kill authFile in b[]
|
||||
|
||||
r.Comma = ':'
|
||||
r.Comment = '#'
|
||||
r.FieldsPerRecord = 4 // username:salt:authCookie:disallowedCmdList (a,b,...)
|
||||
for {
|
||||
record, err := r.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if username == record[0] {
|
||||
tmp, _ := bcrypt.Hash(auth, record[1])
|
||||
if tmp == record[2] {
|
||||
valid = true
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
473
hkexnet.go
473
hkexnet.go
|
|
@ -1,473 +0,0 @@
|
|||
// hkexnet.go - net.Conn compatible channel setup with encrypted/HMAC
|
||||
// negotiation
|
||||
|
||||
// Copyright (c) 2017-2018 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
|
||||
package hkexsh
|
||||
|
||||
// Implementation of HKEx-wrapped versions of the golang standard
|
||||
// net package interfaces, allowing clients and servers to simply replace
|
||||
// 'net.Dial' and 'net.Listen' with 'hkex.Dial' and 'hkex.Listen'.
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"log"
|
||||
"math/big"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
CSONone = iota // No error, normal packet
|
||||
CSOHmacInvalid // HMAC mismatch detected on remote end
|
||||
CSOTermSize // set term size (rows:cols)
|
||||
CSOChaff // Dummy packet, do not pass beyond decryption
|
||||
)
|
||||
|
||||
/*---------------------------------------------------------------------*/
|
||||
|
||||
type WinSize struct {
|
||||
Rows uint16
|
||||
Cols uint16
|
||||
}
|
||||
|
||||
// Conn is a HKex connection - a drop-in replacement for net.Conn
|
||||
type Conn struct {
|
||||
c net.Conn // which also implements io.Reader, io.Writer, ...
|
||||
h *HerraduraKEx
|
||||
cipheropts uint32 // post-KEx cipher/hmac options
|
||||
opts uint32 // post-KEx protocol options (caller-defined)
|
||||
WinCh chan WinSize
|
||||
Rows uint16
|
||||
Cols uint16
|
||||
r cipher.Stream //read cipherStream
|
||||
rm hash.Hash
|
||||
w cipher.Stream //write cipherStream
|
||||
wm hash.Hash
|
||||
dBuf *bytes.Buffer //decrypt buffer for Read()
|
||||
}
|
||||
|
||||
// ConnOpts returns the cipher/hmac options value, which is sent to the
|
||||
// peer but is not itself part of the KEx.
|
||||
//
|
||||
// (Used for protocol-level negotiations after KEx such as
|
||||
// cipher/HMAC algorithm options etc.)
|
||||
func (c Conn) ConnOpts() uint32 {
|
||||
return c.cipheropts
|
||||
}
|
||||
|
||||
// SetConnOpts sets the cipher/hmac options value, which is sent to the
|
||||
// peer as part of KEx but not part of the KEx itself.
|
||||
//
|
||||
// opts - bitfields for cipher and hmac alg. to use after KEx
|
||||
func (c *Conn) SetConnOpts(copts uint32) {
|
||||
c.cipheropts = copts
|
||||
}
|
||||
|
||||
// Opts returns the protocol options value, which is sent to the peer
|
||||
// but is not itself part of the KEx or connection (cipher/hmac) setup.
|
||||
//
|
||||
// Consumers of this lib may use this for protocol-level options not part
|
||||
// of the KEx or encryption info used by the connection.
|
||||
func (c Conn) Opts() uint32 {
|
||||
return c.opts
|
||||
}
|
||||
|
||||
// SetOpts sets the protocol options value, which is sent to the peer
|
||||
// but is not itself part of the KEx or connection (cipher/hmac) setup.
|
||||
//
|
||||
// Consumers of this lib may use this for protocol-level options not part
|
||||
// of the KEx of encryption info used by the connection.
|
||||
//
|
||||
// opts - a uint32, caller-defined
|
||||
func (c *Conn) SetOpts(opts uint32) {
|
||||
c.opts = opts
|
||||
}
|
||||
|
||||
func (c *Conn) applyConnExtensions(extensions ...string) {
|
||||
for _, s := range extensions {
|
||||
switch s {
|
||||
case "C_AES_256":
|
||||
log.Println("[extension arg = C_AES_256]")
|
||||
c.cipheropts &= (0xFFFFFF00)
|
||||
c.cipheropts |= CAlgAES256
|
||||
break
|
||||
case "C_TWOFISH_128":
|
||||
log.Println("[extension arg = C_TWOFISH_128]")
|
||||
c.cipheropts &= (0xFFFFFF00)
|
||||
c.cipheropts |= CAlgTwofish128
|
||||
break
|
||||
case "C_BLOWFISH_64":
|
||||
log.Println("[extension arg = C_BLOWFISH_64]")
|
||||
c.cipheropts &= (0xFFFFFF00)
|
||||
c.cipheropts |= CAlgBlowfish64
|
||||
break
|
||||
case "H_SHA256":
|
||||
log.Println("[extension arg = H_SHA256]")
|
||||
c.cipheropts &= (0xFFFF00FF)
|
||||
c.cipheropts |= (HmacSHA256 << 8)
|
||||
break
|
||||
default:
|
||||
log.Printf("[Dial ext \"%s\" ignored]\n", s)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dial as net.Dial(), but with implicit HKEx PeerD read on connect
|
||||
// Can be called like net.Dial(), defaulting to C_AES_256/H_SHA256,
|
||||
// or additional option arguments can be passed amongst the following:
|
||||
//
|
||||
// "C_AES_256" | "C_TWOFISH_128"
|
||||
//
|
||||
// "H_SHA256"
|
||||
func Dial(protocol string, ipport string, extensions ...string) (hc *Conn, err error) {
|
||||
// Open raw Conn c
|
||||
c, err := net.Dial(protocol, ipport)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Init hkexnet.Conn hc over net.Conn c
|
||||
hc = &Conn{c: c, h: New(0, 0), dBuf: new(bytes.Buffer)}
|
||||
hc.applyConnExtensions(extensions...)
|
||||
|
||||
// Send hkexnet.Conn parameters to remote side
|
||||
// d is value for Herradura key exchange
|
||||
fmt.Fprintf(c, "0x%s\n%08x:%08x\n", hc.h.d.Text(16),
|
||||
hc.cipheropts, hc.opts)
|
||||
|
||||
d := big.NewInt(0)
|
||||
_, err = fmt.Fscanln(c, d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = fmt.Fscanf(c, "%08x:%08x\n",
|
||||
&hc.cipheropts, &hc.opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hc.h.PeerD = d
|
||||
log.Printf("** D:%s\n", hc.h.d.Text(16))
|
||||
log.Printf("**(c)** peerD:%s\n", hc.h.PeerD.Text(16))
|
||||
hc.h.FA()
|
||||
log.Printf("**(c)** FA:%s\n", hc.h.fa)
|
||||
|
||||
hc.r, hc.rm, err = hc.getStream(hc.h.fa)
|
||||
hc.w, hc.wm, err = hc.getStream(hc.h.fa)
|
||||
return
|
||||
}
|
||||
|
||||
// Close a hkex.Conn
|
||||
func (c Conn) Close() (err error) {
|
||||
err = c.c.Close()
|
||||
log.Println("[Conn Closing]")
|
||||
return
|
||||
}
|
||||
|
||||
// LocalAddr returns the local network address.
|
||||
func (c Conn) LocalAddr() net.Addr {
|
||||
return c.c.LocalAddr()
|
||||
}
|
||||
|
||||
// RemoteAddr returns the remote network address.
|
||||
func (c Conn) RemoteAddr() net.Addr {
|
||||
return c.c.RemoteAddr()
|
||||
}
|
||||
|
||||
// SetDeadline sets the read and write deadlines associated
|
||||
// with the connection. It is equivalent to calling both
|
||||
// SetReadDeadline and SetWriteDeadline.
|
||||
//
|
||||
// A deadline is an absolute time after which I/O operations
|
||||
// fail with a timeout (see type Error) instead of
|
||||
// blocking. The deadline applies to all future and pending
|
||||
// I/O, not just the immediately following call to Read or
|
||||
// Write. After a deadline has been exceeded, the connection
|
||||
// can be refreshed by setting a deadline in the future.
|
||||
//
|
||||
// An idle timeout can be implemented by repeatedly extending
|
||||
// the deadline after successful Read or Write calls.
|
||||
//
|
||||
// A zero value for t means I/O operations will not time out.
|
||||
func (c Conn) SetDeadline(t time.Time) error {
|
||||
return c.SetDeadline(t)
|
||||
}
|
||||
|
||||
// SetWriteDeadline sets the deadline for future Write calls
|
||||
// and any currently-blocked Write call.
|
||||
// Even if write times out, it may return n > 0, indicating that
|
||||
// some of the data was successfully written.
|
||||
// A zero value for t means Write will not time out.
|
||||
func (c Conn) SetWriteDeadline(t time.Time) error {
|
||||
return c.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
// SetReadDeadline sets the deadline for future Read calls
|
||||
// and any currently-blocked Read call.
|
||||
// A zero value for t means Read will not time out.
|
||||
func (c Conn) SetReadDeadline(t time.Time) error {
|
||||
return c.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
/*---------------------------------------------------------------------*/
|
||||
|
||||
// HKExListener is a Listener conforming to net.Listener
|
||||
//
|
||||
// See go doc net.Listener
|
||||
type HKExListener struct {
|
||||
l net.Listener
|
||||
}
|
||||
|
||||
// Listen for a connection
|
||||
//
|
||||
// See go doc net.Listen
|
||||
func Listen(protocol string, ipport string) (hl HKExListener, e error) {
|
||||
l, err := net.Listen(protocol, ipport)
|
||||
if err != nil {
|
||||
return HKExListener{nil}, err
|
||||
}
|
||||
log.Println("[Listening]")
|
||||
hl.l = l
|
||||
return
|
||||
}
|
||||
|
||||
// Close a hkex Listener - closes the Listener.
|
||||
// Any blocked Accept operations will be unblocked and return errors.
|
||||
//
|
||||
// See go doc net.Listener.Close
|
||||
func (hl HKExListener) Close() error {
|
||||
log.Println("[Listener Closed]")
|
||||
return hl.l.Close()
|
||||
}
|
||||
|
||||
// Addr returns a the listener's network address.
|
||||
//
|
||||
// See go doc net.Listener.Addr
|
||||
func (hl HKExListener) Addr() net.Addr {
|
||||
return hl.l.Addr()
|
||||
}
|
||||
|
||||
// Accept a client connection, conforming to net.Listener.Accept()
|
||||
//
|
||||
// See go doc net.Listener.Accept
|
||||
func (hl HKExListener) Accept() (hc Conn, err error) {
|
||||
// Open raw Conn c
|
||||
c, err := hl.l.Accept()
|
||||
if err != nil {
|
||||
return Conn{c: nil, h: nil, cipheropts: 0, opts: 0,
|
||||
r: nil, w: nil}, err
|
||||
}
|
||||
log.Println("[Accepted]")
|
||||
|
||||
hc = Conn{c: c, h: New(0, 0), WinCh: make(chan WinSize, 1),
|
||||
dBuf: new(bytes.Buffer)}
|
||||
|
||||
// Read in hkexnet.Conn parameters over raw Conn c
|
||||
// d is value for Herradura key exchange
|
||||
d := big.NewInt(0)
|
||||
_, err = fmt.Fscanln(c, d)
|
||||
log.Printf("[Got d:%v]", d)
|
||||
if err != nil {
|
||||
return hc, err
|
||||
}
|
||||
_, err = fmt.Fscanf(c, "%08x:%08x\n",
|
||||
&hc.cipheropts, &hc.opts)
|
||||
log.Printf("[Got cipheropts, opts:%v, %v]", hc.cipheropts, hc.opts)
|
||||
if err != nil {
|
||||
return hc, err
|
||||
}
|
||||
hc.h.PeerD = d
|
||||
log.Printf("** D:%s\n", hc.h.d.Text(16))
|
||||
log.Printf("**(s)** peerD:%s\n", hc.h.PeerD.Text(16))
|
||||
hc.h.FA()
|
||||
log.Printf("**(s)** FA:%s\n", hc.h.fa)
|
||||
|
||||
fmt.Fprintf(c, "0x%s\n%08x:%08x\n", hc.h.d.Text(16),
|
||||
hc.cipheropts, hc.opts)
|
||||
|
||||
hc.r, hc.rm, err = hc.getStream(hc.h.fa)
|
||||
hc.w, hc.wm, err = hc.getStream(hc.h.fa)
|
||||
return
|
||||
}
|
||||
|
||||
/*---------------------------------------------------------------------*/
|
||||
|
||||
// Read into a byte slice
|
||||
//
|
||||
// See go doc io.Reader
|
||||
func (c Conn) Read(b []byte) (n int, err error) {
|
||||
//log.Printf("[Decrypting...]\r\n")
|
||||
log.Printf("Read() requests %d bytes\n", len(b))
|
||||
|
||||
for {
|
||||
//log.Printf("c.dBuf.Len(): %d\n", c.dBuf.Len())
|
||||
if c.dBuf.Len() > 0 /* len(b) */ {
|
||||
break
|
||||
}
|
||||
|
||||
var ctrlStatOp uint8
|
||||
var hmacIn [4]uint8
|
||||
var payloadLen uint32
|
||||
|
||||
// Read ctrl/status opcode (CSOHmacInvalid on hmac mismatch)
|
||||
err = binary.Read(c.c, binary.BigEndian, &ctrlStatOp)
|
||||
log.Printf("[ctrlStatOp: %v]\n", ctrlStatOp)
|
||||
if ctrlStatOp == CSOHmacInvalid {
|
||||
// Other side indicated channel tampering, close channel
|
||||
c.Close()
|
||||
return 1, errors.New("** ALERT - remote end detected HMAC mismatch - possible channel tampering **")
|
||||
}
|
||||
|
||||
// Read the hmac and payload len first
|
||||
err = binary.Read(c.c, binary.BigEndian, &hmacIn)
|
||||
// Normal client 'exit' from interactive session will cause
|
||||
// (on server side) err.Error() == "<iface/addr info ...>: use of closed network connection"
|
||||
if err != nil {
|
||||
if !strings.HasSuffix(err.Error(), "use of closed network connection") {
|
||||
log.Println("unexpected Read() err:", err)
|
||||
} else {
|
||||
log.Println("[Client hung up]")
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
|
||||
err = binary.Read(c.c, binary.BigEndian, &payloadLen)
|
||||
if err != nil {
|
||||
if err.Error() != "EOF" {
|
||||
panic(err)
|
||||
// Cannot just return 0, err here - client won't hang up properly
|
||||
// when 'exit' from shell. TODO: try server sending ctrlStatOp to
|
||||
// indicate to Reader? -rlm 20180428
|
||||
}
|
||||
}
|
||||
|
||||
if payloadLen > 16384 {
|
||||
log.Printf("[Insane payloadLen:%v]\n", payloadLen)
|
||||
c.Close()
|
||||
return 1, errors.New("Insane payloadLen")
|
||||
}
|
||||
//log.Println("payloadLen:", payloadLen)
|
||||
|
||||
var payloadBytes = make([]byte, payloadLen)
|
||||
n, err = io.ReadFull(c.c, payloadBytes)
|
||||
//log.Print(" << Read ", n, " payloadBytes")
|
||||
|
||||
// Normal client 'exit' from interactive session will cause
|
||||
// (on server side) err.Error() == "<iface/addr info ...>: use of closed network connection"
|
||||
if err != nil && err.Error() != "EOF" {
|
||||
if !strings.HasSuffix(err.Error(), "use of closed network connection") {
|
||||
log.Println("unexpected Read() err:", err)
|
||||
} else {
|
||||
log.Println("[Client hung up]")
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf(" <:ctext:\r\n%s\r\n", hex.Dump(payloadBytes[:n]))
|
||||
|
||||
db := bytes.NewBuffer(payloadBytes[:n]) //copying payloadBytes to db
|
||||
// The StreamReader acts like a pipe, decrypting
|
||||
// whatever is available and forwarding the result
|
||||
// to the parameter of Read() as a normal io.Reader
|
||||
rs := &cipher.StreamReader{S: c.r, R: db}
|
||||
// The caller isn't necessarily reading the full payload so we need
|
||||
// to decrypt ot an intermediate buffer, draining it on demand of caller
|
||||
decryptN, err := rs.Read(payloadBytes)
|
||||
log.Printf(" <-ptext:\r\n%s\r\n", hex.Dump(payloadBytes[:n]))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Throw away pkt if it's chaff (ie., caller to Read() won't see this data)
|
||||
if ctrlStatOp == CSOChaff {
|
||||
log.Printf("[Chaff pkt]\n")
|
||||
} else if ctrlStatOp == CSOTermSize {
|
||||
fmt.Sscanf(string(payloadBytes), "%d %d", &c.Rows, &c.Cols)
|
||||
log.Printf("[TermSize pkt: rows %v cols %v]\n", c.Rows, c.Cols)
|
||||
c.WinCh <- WinSize{c.Rows, c.Cols}
|
||||
} else {
|
||||
c.dBuf.Write(payloadBytes)
|
||||
//log.Printf("c.dBuf: %s\n", hex.Dump(c.dBuf.Bytes()))
|
||||
}
|
||||
|
||||
// Re-calculate hmac, compare with received value
|
||||
c.rm.Write(payloadBytes)
|
||||
hTmp := c.rm.Sum(nil)[0:4]
|
||||
log.Printf("<%04x) HMAC:(i)%s (c)%02x\r\n", decryptN, hex.EncodeToString([]byte(hmacIn[0:])), hTmp)
|
||||
|
||||
// Log alert if hmac didn't match, corrupted channel
|
||||
if !bytes.Equal(hTmp, []byte(hmacIn[0:])) /*|| hmacIn[0] > 0xf8*/ {
|
||||
fmt.Println("** ALERT - detected HMAC mismatch, possible channel tampering **")
|
||||
_, _ = c.c.Write([]byte{CSOHmacInvalid})
|
||||
}
|
||||
}
|
||||
|
||||
retN := c.dBuf.Len()
|
||||
if retN > len(b) {
|
||||
retN = len(b)
|
||||
}
|
||||
|
||||
log.Printf("Read() got %d bytes\n", retN)
|
||||
copy(b, c.dBuf.Next(retN))
|
||||
//log.Printf("As Read() returns, c.dBuf is %d long: %s\n", c.dBuf.Len(), hex.Dump(c.dBuf.Bytes()))
|
||||
return retN, nil
|
||||
}
|
||||
|
||||
// Write a byte slice
|
||||
//
|
||||
// See go doc io.Writer
|
||||
func (c Conn) Write(b []byte) (n int, err error) {
|
||||
return c.WritePacket(b, CSONone)
|
||||
}
|
||||
|
||||
// Write a byte slice with specified ctrlStatusOp byte
|
||||
func (c Conn) WritePacket(b []byte, op byte) (n int, err error) {
|
||||
//log.Printf("[Encrypting...]\r\n")
|
||||
var hmacOut []uint8
|
||||
var payloadLen uint32
|
||||
|
||||
log.Printf(" :>ptext:\r\n%s\r\n", hex.Dump(b))
|
||||
|
||||
payloadLen = uint32(len(b))
|
||||
|
||||
// Calculate hmac on payload
|
||||
c.wm.Write(b)
|
||||
hmacOut = c.wm.Sum(nil)[0:4]
|
||||
|
||||
log.Printf(" (%04x> HMAC(o):%s\r\n", payloadLen, hex.EncodeToString(hmacOut))
|
||||
|
||||
var wb bytes.Buffer
|
||||
// The StreamWriter acts like a pipe, forwarding whatever is
|
||||
// written to it through the cipher, encrypting as it goes
|
||||
ws := &cipher.StreamWriter{S: c.w, W: &wb}
|
||||
_, err = ws.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Printf(" ->ctext:\r\n%s\r\n", hex.Dump(wb.Bytes()))
|
||||
|
||||
ctrlStatOp := op
|
||||
_ = binary.Write(c.c, binary.BigEndian, &ctrlStatOp)
|
||||
|
||||
// Write hmac LSB, payloadLen followed by payload
|
||||
_ = binary.Write(c.c, binary.BigEndian, hmacOut)
|
||||
_ = binary.Write(c.c, binary.BigEndian, payloadLen)
|
||||
|
||||
n, err = c.c.Write(wb.Bytes())
|
||||
if err != nil {
|
||||
//panic(err)
|
||||
log.Println(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
240
hkexsh/hkexsh.go
240
hkexsh/hkexsh.go
|
|
@ -1,240 +0,0 @@
|
|||
// hkexsh client
|
||||
//
|
||||
// Copyright (c) 2017-2018 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"os/user"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
hkexsh "blitter.com/go/hkexsh"
|
||||
isatty "github.com/mattn/go-isatty"
|
||||
)
|
||||
|
||||
type cmdSpec struct {
|
||||
op []byte
|
||||
who []byte
|
||||
cmd []byte
|
||||
authCookie []byte
|
||||
status int
|
||||
}
|
||||
|
||||
// get terminal size using 'stty' command
|
||||
// (Most portable btwn Linux and MSYS/win32, but
|
||||
// TODO: remove external dep on 'stty' utility)
|
||||
func getTermSize() (rows int, cols int, err error) {
|
||||
cmd := exec.Command("stty", "size")
|
||||
cmd.Stdin = os.Stdin
|
||||
out, err := cmd.Output()
|
||||
//fmt.Printf("out: %#v\n", string(out))
|
||||
//fmt.Printf("err: %#v\n", err)
|
||||
|
||||
fmt.Sscanf(string(out), "%d %d\n", &rows, &cols)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Demo of a simple client that dials up to a simple test server to
|
||||
// send data.
|
||||
//
|
||||
// While conforming to the basic net.Conn interface HKex.Conn has extra
|
||||
// capabilities designed to allow apps to define connection options,
|
||||
// encryption/hmac settings and operations across the encrypted channel.
|
||||
//
|
||||
// Initial setup is the same as using plain net.Dial(), but one may
|
||||
// specify extra extension tags (strings) to set the cipher and hmac
|
||||
// setting desired; as well as the intended operation mode for the
|
||||
// connection (app-specific, passed through to the server to use or
|
||||
// ignore at its discretion).
|
||||
func main() {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
var dbg bool
|
||||
var cAlg string
|
||||
var hAlg string
|
||||
var server string
|
||||
var cmdStr string
|
||||
var altUser string
|
||||
var authCookie string
|
||||
isInteractive := false
|
||||
|
||||
flag.StringVar(&cAlg, "c", "C_AES_256", "cipher [\"C_AES_256\" | \"C_TWOFISH_128\" | \"C_BLOWFISH_64\"]")
|
||||
flag.StringVar(&hAlg, "h", "H_SHA256", "hmac [\"H_SHA256\"]")
|
||||
flag.StringVar(&server, "s", "localhost:2000", "server hostname/address[:port]")
|
||||
flag.StringVar(&cmdStr, "x", "", "command to run (default empty - interactive shell)")
|
||||
flag.StringVar(&altUser, "u", "", "specify alternate user")
|
||||
flag.StringVar(&authCookie, "a", "", "auth cookie (MultiCheese3999(tm) 2FA cookie")
|
||||
flag.BoolVar(&dbg, "d", false, "debug logging")
|
||||
flag.Parse()
|
||||
|
||||
if dbg {
|
||||
log.SetOutput(os.Stdout)
|
||||
} else {
|
||||
log.SetOutput(ioutil.Discard)
|
||||
}
|
||||
|
||||
conn, err := hkexsh.Dial("tcp", server, cAlg, hAlg)
|
||||
if err != nil {
|
||||
fmt.Println("Err!")
|
||||
panic(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
// From this point on, conn is a secure encrypted channel
|
||||
|
||||
rows := 0
|
||||
cols := 0
|
||||
|
||||
// Set stdin in raw mode if it's an interactive session
|
||||
// TODO: send flag to server side indicating this
|
||||
// affects shell command used
|
||||
var oldState *hkexsh.State
|
||||
if isatty.IsTerminal(os.Stdin.Fd()) {
|
||||
oldState, err = hkexsh.MakeRaw(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer func() { _ = hkexsh.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort.
|
||||
} else {
|
||||
log.Println("NOT A TTY")
|
||||
}
|
||||
|
||||
var uname string
|
||||
if len(altUser) == 0 {
|
||||
u, _ := user.Current()
|
||||
uname = u.Username
|
||||
} else {
|
||||
uname = altUser
|
||||
}
|
||||
|
||||
var op []byte
|
||||
if len(cmdStr) == 0 {
|
||||
op = []byte{'s'}
|
||||
isInteractive = true
|
||||
} else if cmdStr == "-" {
|
||||
op = []byte{'c'}
|
||||
cmdStdin, err := ioutil.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cmdStr = strings.Trim(string(cmdStdin), "\r\n")
|
||||
} else {
|
||||
op = []byte{'c'}
|
||||
}
|
||||
|
||||
if len(authCookie) == 0 {
|
||||
fmt.Printf("Gimme cookie:")
|
||||
ab, err := hkexsh.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Printf("\r\n")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
authCookie = string(ab)
|
||||
}
|
||||
|
||||
rec := &cmdSpec{
|
||||
op: op,
|
||||
who: []byte(uname),
|
||||
cmd: []byte(cmdStr),
|
||||
authCookie: []byte(authCookie),
|
||||
status: 0}
|
||||
|
||||
_, err = fmt.Fprintf(conn, "%d %d %d %d\n",
|
||||
len(rec.op), len(rec.who), len(rec.cmd), len(rec.authCookie))
|
||||
|
||||
_, err = conn.Write(rec.op)
|
||||
_, err = conn.Write(rec.who)
|
||||
_, err = conn.Write(rec.cmd)
|
||||
_, err = conn.Write(rec.authCookie)
|
||||
|
||||
//client reader (from server) goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
// By deferring a call to wg.Done(),
|
||||
// each goroutine guarantees that it marks
|
||||
// its direction's stream as finished.
|
||||
//
|
||||
// Whichever direction's goroutine finishes first
|
||||
// will call wg.Done() once more, explicitly, to
|
||||
// hang up on the other side, so that this client
|
||||
// exits immediately on an EOF from either side.
|
||||
defer wg.Done()
|
||||
|
||||
// io.Copy() expects EOF so this will
|
||||
// exit with inerr == nil
|
||||
_, inerr := io.Copy(os.Stdout, conn)
|
||||
if inerr != nil {
|
||||
if inerr.Error() != "EOF" {
|
||||
fmt.Println(inerr)
|
||||
_ = hkexsh.Restore(int(os.Stdin.Fd()), oldState) // Best effort.
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
if isInteractive {
|
||||
log.Println("[Got EOF]")
|
||||
wg.Done() // server hung up, close WaitGroup to exit client
|
||||
}
|
||||
}()
|
||||
|
||||
if isInteractive {
|
||||
// Handle pty resizes (notify server side)
|
||||
ch := make(chan os.Signal, 1)
|
||||
signal.Notify(ch, syscall.SIGWINCH)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
for range ch {
|
||||
// Query client's term size so we can communicate it to server
|
||||
// pty after interactive session starts
|
||||
rows, cols, err = getTermSize()
|
||||
log.Printf("[rows %v cols %v]\n", rows, cols)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
termSzPacket := fmt.Sprintf("%d %d", rows, cols)
|
||||
conn.WritePacket([]byte(termSzPacket), hkexsh.CSOTermSize)
|
||||
}
|
||||
}()
|
||||
ch <- syscall.SIGWINCH // Initial resize.
|
||||
|
||||
// client writer (to server) goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
// io.Copy() expects EOF so this will
|
||||
// exit with outerr == nil
|
||||
_, outerr := io.Copy(conn, os.Stdin)
|
||||
if outerr != nil {
|
||||
log.Println(outerr)
|
||||
if outerr.Error() != "EOF" {
|
||||
fmt.Println(outerr)
|
||||
_ = hkexsh.Restore(int(os.Stdin.Fd()), oldState) // Best effort.
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
log.Println("[Sent EOF]")
|
||||
wg.Done() // client hung up, close WaitGroup to exit client
|
||||
}()
|
||||
}
|
||||
|
||||
// Wait until both stdin and stdout goroutines finish
|
||||
wg.Wait()
|
||||
}
|
||||
|
|
@ -1,274 +0,0 @@
|
|||
// hkexshd server
|
||||
//
|
||||
// Copyright (c) 2017-2018 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"syscall"
|
||||
|
||||
hkexsh "blitter.com/go/hkexsh"
|
||||
"blitter.com/go/hkexsh/spinsult"
|
||||
"github.com/kr/pty"
|
||||
)
|
||||
|
||||
type cmdSpec struct {
|
||||
op []byte
|
||||
who []byte
|
||||
cmd []byte
|
||||
authCookie []byte
|
||||
termRows []byte
|
||||
termCols []byte
|
||||
status int
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
// Run a command (via os.exec) as a specific user
|
||||
//
|
||||
// Uses ptys to support commands which expect a terminal.
|
||||
func runCmdAs(who string, cmd string, conn hkex.Conn) (err error) {
|
||||
u, _ := user.Lookup(who)
|
||||
var uid, gid uint32
|
||||
fmt.Sscanf(u.Uid, "%d", &uid)
|
||||
fmt.Sscanf(u.Gid, "%d", &gid)
|
||||
fmt.Println("uid:", uid, "gid:", gid)
|
||||
|
||||
args := strings.Split(cmd, " ")
|
||||
arg0 := args[0]
|
||||
args = args[1:]
|
||||
c := exec.Command(arg0, args...)
|
||||
c.SysProcAttr = &syscall.SysProcAttr{}
|
||||
c.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}
|
||||
c.Stdin = conn
|
||||
c.Stdout = conn
|
||||
c.Stderr = conn
|
||||
|
||||
// Start the command with a pty.
|
||||
ptmx, err := pty.Start(c) // returns immediately with ptmx file
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Make sure to close the pty at the end.
|
||||
defer func() { _ = ptmx.Close() }() // Best effort.
|
||||
// Copy stdin to the pty and the pty to stdout.
|
||||
go func() { _, _ = io.Copy(ptmx, conn) }()
|
||||
_, _ = io.Copy(conn, ptmx)
|
||||
|
||||
//err = c.Run() // returns when c finishes.
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Command finished with error: %v", err)
|
||||
log.Printf("[%s]\n", cmd)
|
||||
}
|
||||
return
|
||||
}
|
||||
*/
|
||||
|
||||
// Run a command (via default shell) as a specific user
|
||||
//
|
||||
// Uses ptys to support commands which expect a terminal.
|
||||
func runShellAs(who string, cmd string, interactive bool, conn hkexsh.Conn) (err error) {
|
||||
u, _ := user.Lookup(who)
|
||||
var uid, gid uint32
|
||||
fmt.Sscanf(u.Uid, "%d", &uid)
|
||||
fmt.Sscanf(u.Gid, "%d", &gid)
|
||||
log.Println("uid:", uid, "gid:", gid)
|
||||
|
||||
// Need to clear server's env and set key vars of the
|
||||
// target user. This isn't perfect (TERM doesn't seem to
|
||||
// work 100%; ANSI/xterm colour isn't working even
|
||||
// if we set "xterm" or "ansi" here; and line count
|
||||
// reported by 'stty -a' defaults to 24 regardless
|
||||
// of client shell window used to run client.
|
||||
// Investigate -- rlm 2018-01-26)
|
||||
os.Clearenv()
|
||||
os.Setenv("HOME", u.HomeDir)
|
||||
os.Setenv("TERM", "vt102") // TODO: server or client option?
|
||||
|
||||
var c *exec.Cmd
|
||||
if interactive {
|
||||
c = exec.Command("/bin/bash", "-i", "-l")
|
||||
} else {
|
||||
c = exec.Command("/bin/bash", "-c", cmd)
|
||||
}
|
||||
//If os.Clearenv() isn't called by server above these will be seen in the
|
||||
//client's session env.
|
||||
//c.Env = []string{"HOME=" + u.HomeDir, "SUDO_GID=", "SUDO_UID=", "SUDO_USER=", "SUDO_COMMAND=", "MAIL=", "LOGNAME="+who}
|
||||
c.Dir = u.HomeDir
|
||||
c.SysProcAttr = &syscall.SysProcAttr{}
|
||||
c.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}
|
||||
c.Stdin = conn
|
||||
c.Stdout = conn
|
||||
c.Stderr = conn
|
||||
|
||||
// Start the command with a pty.
|
||||
ptmx, err := pty.Start(c) // returns immediately with ptmx file
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Make sure to close the pty at the end.
|
||||
defer func() { _ = ptmx.Close() }() // Best effort.
|
||||
|
||||
// Watch for term resizes
|
||||
go func() {
|
||||
for sz := range conn.WinCh {
|
||||
log.Printf("[Setting term size to: %v %v]\n", sz.Rows, sz.Cols)
|
||||
pty.Setsize(ptmx, &pty.Winsize{Rows: sz.Rows, Cols: sz.Cols})
|
||||
}
|
||||
}()
|
||||
|
||||
// Copy stdin to the pty.. (bgnd goroutine)
|
||||
go func() {
|
||||
_, _ = io.Copy(ptmx, conn)
|
||||
}()
|
||||
// ..and the pty to stdout.
|
||||
_, _ = io.Copy(conn, ptmx)
|
||||
|
||||
//err = c.Run() // returns when c finishes.
|
||||
|
||||
log.Printf("[%s]\n", cmd)
|
||||
if err != nil {
|
||||
log.Printf("Command finished with error: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func rejectUserMsg() string {
|
||||
return "Begone, " + spinsult.GetSentence() + "\r\n"
|
||||
}
|
||||
|
||||
// Demo of a simple server that listens and spawns goroutines for each
|
||||
// connecting client. Note this code is identical to standard tcp
|
||||
// server code, save for declaring 'hkex' rather than 'net'
|
||||
// Listener and Conns. The KEx and encrypt/decrypt is done within the type.
|
||||
// Compare to 'serverp.go' in this directory to see the equivalence.
|
||||
func main() {
|
||||
var dbg bool
|
||||
var laddr string
|
||||
|
||||
flag.StringVar(&laddr, "l", ":2000", "interface[:port] to listen")
|
||||
flag.BoolVar(&dbg, "d", false, "debug logging")
|
||||
flag.Parse()
|
||||
|
||||
if dbg {
|
||||
log.SetOutput(os.Stdout)
|
||||
} else {
|
||||
log.SetOutput(ioutil.Discard)
|
||||
}
|
||||
|
||||
// Listen on TCP port 2000 on all available unicast and
|
||||
// anycast IP addresses of the local system.
|
||||
l, err := hkexsh.Listen("tcp", laddr)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
log.Println("Serving on", laddr)
|
||||
for {
|
||||
// Wait for a connection.
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
log.Printf("Accept() got error(%v), hanging up.\n", err)
|
||||
conn.Close()
|
||||
//log.Fatal(err)
|
||||
} else {
|
||||
log.Println("Accepted client")
|
||||
|
||||
// Handle the connection in a new goroutine.
|
||||
// The loop then returns to accepting, so that
|
||||
// multiple connections may be served concurrently.
|
||||
go func(c hkexsh.Conn) (e error) {
|
||||
defer c.Close()
|
||||
|
||||
//We use io.ReadFull() here to guarantee we consume
|
||||
//just the data we want for the cmdSpec, and no more.
|
||||
//Otherwise data will be sitting in the channel that isn't
|
||||
//passed down to the command handlers.
|
||||
var rec cmdSpec
|
||||
var len1, len2, len3, len4 uint32
|
||||
|
||||
n, err := fmt.Fscanf(c, "%d %d %d %d\n", &len1, &len2, &len3, &len4)
|
||||
log.Printf("cmdSpec read:%d %d %d %d\n", len1, len2, len3, len4)
|
||||
|
||||
if err != nil || n < 4 {
|
||||
log.Println("[Bad cmdSpec fmt]")
|
||||
return err
|
||||
}
|
||||
//fmt.Printf(" lens:%d %d %d %d\n", len1, len2, len3, len4)
|
||||
|
||||
rec.op = make([]byte, len1, len1)
|
||||
_, err = io.ReadFull(c, rec.op)
|
||||
if err != nil {
|
||||
log.Println("[Bad cmdSpec.op]")
|
||||
return err
|
||||
}
|
||||
rec.who = make([]byte, len2, len2)
|
||||
_, err = io.ReadFull(c, rec.who)
|
||||
if err != nil {
|
||||
log.Println("[Bad cmdSpec.who]")
|
||||
return err
|
||||
}
|
||||
|
||||
rec.cmd = make([]byte, len3, len3)
|
||||
_, err = io.ReadFull(c, rec.cmd)
|
||||
if err != nil {
|
||||
log.Println("[Bad cmdSpec.cmd]")
|
||||
return err
|
||||
}
|
||||
|
||||
rec.authCookie = make([]byte, len4, len4)
|
||||
_, err = io.ReadFull(c, rec.authCookie)
|
||||
if err != nil {
|
||||
log.Println("[Bad cmdSpec.authCookie]")
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("[cmdSpec: op:%c who:%s cmd:%s auth:****]\n",
|
||||
rec.op[0], string(rec.who), string(rec.cmd))
|
||||
|
||||
valid, allowedCmds := hkexsh.AuthUser(string(rec.who), string(rec.authCookie), "/etc/hkexsh.passwd")
|
||||
if !valid {
|
||||
log.Println("Invalid user", string(rec.who))
|
||||
c.Write([]byte(rejectUserMsg()))
|
||||
return
|
||||
}
|
||||
log.Printf("[allowedCmds:%s]\n", allowedCmds)
|
||||
|
||||
if rec.op[0] == 'c' {
|
||||
// Non-interactive command
|
||||
log.Println("[Running command]")
|
||||
runShellAs(string(rec.who), string(rec.cmd), false, conn)
|
||||
// Returned hopefully via an EOF or exit/logout;
|
||||
// Clear current op so user can enter next, or EOF
|
||||
rec.op[0] = 0
|
||||
log.Println("[Command complete]")
|
||||
} else if rec.op[0] == 's' {
|
||||
log.Println("[Running shell]")
|
||||
runShellAs(string(rec.who), string(rec.cmd), true, conn)
|
||||
// Returned hopefully via an EOF or exit/logout;
|
||||
// Clear current op so user can enter next, or EOF
|
||||
rec.op[0] = 0
|
||||
log.Println("[Exiting shell]")
|
||||
} else {
|
||||
log.Println("[Bad cmdSpec]")
|
||||
}
|
||||
return
|
||||
}(conn)
|
||||
} // Accept() success
|
||||
} //endfor
|
||||
log.Println("[Exiting]")
|
||||
}
|
||||
12
logger/Makefile
Normal file
12
logger/Makefile
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
.PHONY: clean all lint
|
||||
|
||||
EXE = $(notdir $(shell pwd))
|
||||
|
||||
all:
|
||||
go build .
|
||||
|
||||
clean:
|
||||
$(RM) $(EXE) $(EXE).exe
|
||||
|
||||
lint:
|
||||
gometalinter --deadline 60s | sort
|
||||
156
logger/logger_bsd.go
Normal file
156
logger/logger_bsd.go
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
// +build freebsd
|
||||
|
||||
// Package logger is a wrapper around UNIX syslog, so that it also may
|
||||
// be wrapped with something else for Windows (Sadly, the stdlib log/syslog
|
||||
// is frozen, and there is no Windows implementation.)
|
||||
package logger
|
||||
|
||||
import (
|
||||
sl "log/syslog"
|
||||
)
|
||||
|
||||
// Priority is the logger priority
|
||||
type Priority = sl.Priority
|
||||
|
||||
// Writer is a syslog Writer
|
||||
type Writer = sl.Writer
|
||||
|
||||
// nolint: golint
|
||||
const (
|
||||
// Severity.
|
||||
|
||||
// From /usr/include/sys/syslog.h.
|
||||
// These are the same on Linux, BSD, and OS X.
|
||||
LOG_EMERG Priority = iota
|
||||
LOG_ALERT
|
||||
LOG_CRIT
|
||||
LOG_ERR
|
||||
LOG_WARNING
|
||||
LOG_NOTICE
|
||||
LOG_INFO
|
||||
LOG_DEBUG
|
||||
)
|
||||
|
||||
// nolint: golint
|
||||
const (
|
||||
// Facility.
|
||||
|
||||
// From /usr/include/sys/syslog.h.
|
||||
// These are the same up to LOG_FTP on Linux, BSD, and OS X.
|
||||
LOG_KERN Priority = iota << 3
|
||||
LOG_USER
|
||||
LOG_MAIL
|
||||
LOG_DAEMON
|
||||
LOG_AUTH
|
||||
LOG_SYSLOG
|
||||
LOG_LPR
|
||||
LOG_NEWS
|
||||
LOG_UUCP
|
||||
LOG_CRON
|
||||
LOG_AUTHPRIV
|
||||
LOG_FTP
|
||||
_ // unused
|
||||
_ // unused
|
||||
_ // unused
|
||||
_ // unused
|
||||
LOG_LOCAL0
|
||||
LOG_LOCAL1
|
||||
LOG_LOCAL2
|
||||
LOG_LOCAL3
|
||||
LOG_LOCAL4
|
||||
LOG_LOCAL5
|
||||
LOG_LOCAL6
|
||||
LOG_LOCAL7
|
||||
)
|
||||
|
||||
var (
|
||||
l *sl.Writer
|
||||
)
|
||||
|
||||
// New returns a new log Writer.
|
||||
func New(flags Priority, tag string) (w *Writer, e error) {
|
||||
w, e = sl.New(flags, tag)
|
||||
l = w
|
||||
return w, e
|
||||
}
|
||||
|
||||
// Alert returns a log Alert error
|
||||
func Alert(s string) error {
|
||||
if l != nil {
|
||||
return l.Alert(s)
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
// LogClose closes the log Writer.
|
||||
func LogClose() error {
|
||||
if l != nil {
|
||||
return l.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogCrit returns a log Alert error
|
||||
func LogCrit(s string) error {
|
||||
if l != nil {
|
||||
return l.Crit(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogDebug returns a log Debug error
|
||||
func LogDebug(s string) error {
|
||||
if l != nil {
|
||||
return l.Debug(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogEmerg returns a log Emerg error
|
||||
func LogEmerg(s string) error {
|
||||
if l != nil {
|
||||
return l.Emerg(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogErr returns a log Err error
|
||||
func LogErr(s string) error {
|
||||
if l != nil {
|
||||
return l.Err(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogInfo returns a log Info error
|
||||
func LogInfo(s string) error {
|
||||
if l != nil {
|
||||
return l.Info(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogNotice returns a log Notice error
|
||||
func LogNotice(s string) error {
|
||||
if l != nil {
|
||||
return l.Notice(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogWarning returns a log Warning error
|
||||
func LogWarning(s string) error {
|
||||
if l != nil {
|
||||
return l.Warning(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogWrite writes to the logger at default level
|
||||
func LogWrite(b []byte) (int, error) {
|
||||
if l != nil {
|
||||
return l.Write(b)
|
||||
}
|
||||
return len(b),nil
|
||||
}
|
||||
156
logger/logger_linux.go
Normal file
156
logger/logger_linux.go
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
// +build linux
|
||||
|
||||
// Package logger is a wrapper around UNIX syslog, so that it also may
|
||||
// be wrapped with something else for Windows (Sadly, the stdlib log/syslog
|
||||
// is frozen, and there is no Windows implementation.)
|
||||
package logger
|
||||
|
||||
import (
|
||||
sl "log/syslog"
|
||||
)
|
||||
|
||||
// Priority is the logger priority
|
||||
type Priority = sl.Priority
|
||||
|
||||
// Writer is a syslog Writer
|
||||
type Writer = sl.Writer
|
||||
|
||||
// nolint: golint
|
||||
const (
|
||||
// Severity.
|
||||
|
||||
// From /usr/include/sys/syslog.h.
|
||||
// These are the same on Linux, BSD, and OS X.
|
||||
LOG_EMERG Priority = iota
|
||||
LOG_ALERT
|
||||
LOG_CRIT
|
||||
LOG_ERR
|
||||
LOG_WARNING
|
||||
LOG_NOTICE
|
||||
LOG_INFO
|
||||
LOG_DEBUG
|
||||
)
|
||||
|
||||
// nolint: golint
|
||||
const (
|
||||
// Facility.
|
||||
|
||||
// From /usr/include/sys/syslog.h.
|
||||
// These are the same up to LOG_FTP on Linux, BSD, and OS X.
|
||||
LOG_KERN Priority = iota << 3
|
||||
LOG_USER
|
||||
LOG_MAIL
|
||||
LOG_DAEMON
|
||||
LOG_AUTH
|
||||
LOG_SYSLOG
|
||||
LOG_LPR
|
||||
LOG_NEWS
|
||||
LOG_UUCP
|
||||
LOG_CRON
|
||||
LOG_AUTHPRIV
|
||||
LOG_FTP
|
||||
_ // unused
|
||||
_ // unused
|
||||
_ // unused
|
||||
_ // unused
|
||||
LOG_LOCAL0
|
||||
LOG_LOCAL1
|
||||
LOG_LOCAL2
|
||||
LOG_LOCAL3
|
||||
LOG_LOCAL4
|
||||
LOG_LOCAL5
|
||||
LOG_LOCAL6
|
||||
LOG_LOCAL7
|
||||
)
|
||||
|
||||
var (
|
||||
l *sl.Writer
|
||||
)
|
||||
|
||||
// New returns a new log Writer.
|
||||
func New(flags Priority, tag string) (w *Writer, e error) {
|
||||
w, e = sl.New(flags, tag)
|
||||
l = w
|
||||
return w, e
|
||||
}
|
||||
|
||||
// Alert returns a log Alert error
|
||||
func Alert(s string) error {
|
||||
if l != nil {
|
||||
return l.Alert(s)
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
// LogClose closes the log Writer.
|
||||
func LogClose() error {
|
||||
if l != nil {
|
||||
return l.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogCrit returns a log Alert error
|
||||
func LogCrit(s string) error {
|
||||
if l != nil {
|
||||
return l.Crit(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogDebug returns a log Debug error
|
||||
func LogDebug(s string) error {
|
||||
if l != nil {
|
||||
return l.Debug(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogEmerg returns a log Emerg error
|
||||
func LogEmerg(s string) error {
|
||||
if l != nil {
|
||||
return l.Emerg(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogErr returns a log Err error
|
||||
func LogErr(s string) error {
|
||||
if l != nil {
|
||||
return l.Err(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogInfo returns a log Info error
|
||||
func LogInfo(s string) error {
|
||||
if l != nil {
|
||||
return l.Info(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogNotice returns a log Notice error
|
||||
func LogNotice(s string) error {
|
||||
if l != nil {
|
||||
return l.Notice(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogWarning returns a log Warning error
|
||||
func LogWarning(s string) error {
|
||||
if l != nil {
|
||||
return l.Warning(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogWrite writes to the logger at default level
|
||||
func LogWrite(b []byte) (int, error) {
|
||||
if l != nil {
|
||||
return l.Write(b)
|
||||
}
|
||||
return len(b),nil
|
||||
}
|
||||
94
logger/logger_windows.go
Normal file
94
logger/logger_windows.go
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
// +build windows
|
||||
|
||||
// Wrapper around UNIX syslog, so that it also may be wrapped
|
||||
// with something else for Windows.
|
||||
package logger
|
||||
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
type Priority = int
|
||||
type Writer = os.File
|
||||
|
||||
|
||||
const (
|
||||
// Severity.
|
||||
|
||||
// From /usr/include/sys/syslog.h.
|
||||
// These are the same on Linux, BSD, and OS X.
|
||||
LOG_EMERG Priority = iota
|
||||
LOG_ALERT
|
||||
LOG_CRIT
|
||||
LOG_ERR
|
||||
LOG_WARNING
|
||||
LOG_NOTICE
|
||||
LOG_INFO
|
||||
LOG_DEBUG
|
||||
)
|
||||
|
||||
const (
|
||||
// Facility.
|
||||
|
||||
// From /usr/include/sys/syslog.h.
|
||||
// These are the same up to LOG_FTP on Linux, BSD, and OS X.
|
||||
LOG_KERN Priority = iota << 3
|
||||
LOG_USER
|
||||
LOG_MAIL
|
||||
LOG_DAEMON
|
||||
LOG_AUTH
|
||||
LOG_SYSLOG
|
||||
LOG_LPR
|
||||
LOG_NEWS
|
||||
LOG_UUCP
|
||||
LOG_CRON
|
||||
LOG_AUTHPRIV
|
||||
LOG_FTP
|
||||
_ // unused
|
||||
_ // unused
|
||||
_ // unused
|
||||
_ // unused
|
||||
LOG_LOCAL0
|
||||
LOG_LOCAL1
|
||||
LOG_LOCAL2
|
||||
LOG_LOCAL3
|
||||
LOG_LOCAL4
|
||||
LOG_LOCAL5
|
||||
LOG_LOCAL6
|
||||
LOG_LOCAL7
|
||||
)
|
||||
|
||||
func New(flags Priority, tag string) (w *Writer, e error) {
|
||||
return os.Stderr, nil
|
||||
}
|
||||
|
||||
func Alert(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogClose() error {
|
||||
return nil
|
||||
}
|
||||
func LogCrit(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogDebug(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogEmerg(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogErr(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogInfo(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogNotice(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogWarning(s string) error {
|
||||
return nil
|
||||
}
|
||||
func LogWrite(b []byte) (int, error) {
|
||||
return len(b), nil
|
||||
}
|
||||
139
session.go
Normal file
139
session.go
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
package xs
|
||||
|
||||
// Package xs - a secure terminal client/server written from scratch in Go
|
||||
//
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
|
||||
// Session info/routines for the HKExSh
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// Session holds essential bookkeeping info about an active session.
|
||||
type Session struct {
|
||||
op []byte
|
||||
who []byte
|
||||
connhost []byte
|
||||
termtype []byte // client initial $TERM
|
||||
cmd []byte
|
||||
authCookie []byte
|
||||
status uint32 // exit status (0-255 is std UNIX status)
|
||||
}
|
||||
|
||||
// Output Session record as a string. Implements Stringer interface.
|
||||
func (h *Session) String() string {
|
||||
return fmt.Sprintf("xs.Session:\nOp:%v\nWho:%v\nCmd:%v\nAuthCookie:%v\nStatus:%v",
|
||||
h.op, h.who, h.cmd, h.AuthCookie(false), h.status)
|
||||
}
|
||||
|
||||
// Op returns the op code of the Session (interactive shell, cmd, ...)
|
||||
func (h Session) Op() []byte {
|
||||
return h.op
|
||||
}
|
||||
|
||||
// SetOp stores the op code desired for a Session.
|
||||
func (h *Session) SetOp(o []byte) {
|
||||
h.op = o
|
||||
}
|
||||
|
||||
// Who returns the user associated with a Session.
|
||||
func (h Session) Who() []byte {
|
||||
return h.who
|
||||
}
|
||||
|
||||
// SetWho sets the username associated with a Session.
|
||||
func (h *Session) SetWho(w []byte) {
|
||||
h.who = w
|
||||
}
|
||||
|
||||
// ConnHost returns the connecting hostname/IP string for a Session.
|
||||
func (h Session) ConnHost() []byte {
|
||||
return h.connhost
|
||||
}
|
||||
|
||||
// SetConnHost stores the connecting hostname/IP string for a Session.
|
||||
func (h *Session) SetConnHost(n []byte) {
|
||||
h.connhost = n
|
||||
}
|
||||
|
||||
// TermType returns the TERM env variable reported by the client initiating
|
||||
// a Session.
|
||||
func (h Session) TermType() []byte {
|
||||
return h.termtype
|
||||
}
|
||||
|
||||
// SetTermType stores the TERM env variable supplied by the client initiating
|
||||
// a Session.
|
||||
func (h *Session) SetTermType(t []byte) {
|
||||
h.termtype = t
|
||||
}
|
||||
|
||||
// Cmd returns the command requested for execution by a client initiating
|
||||
// the Session.
|
||||
func (h Session) Cmd() []byte {
|
||||
return h.cmd
|
||||
}
|
||||
|
||||
// SetCmd stores the command request by the client for execution when initiating
|
||||
// the Session.
|
||||
func (h *Session) SetCmd(c []byte) {
|
||||
h.cmd = c
|
||||
}
|
||||
|
||||
// AuthCookie returns the authcookie (essentially the password) used for
|
||||
// authorization of the Session. This return value is censored unless
|
||||
// reallyShow is true (so dumps of Session Info do not accidentally leak it).
|
||||
func (h Session) AuthCookie(reallyShow bool) []byte {
|
||||
if reallyShow {
|
||||
return h.authCookie
|
||||
}
|
||||
return []byte("**REDACTED**")
|
||||
}
|
||||
|
||||
// SetAuthCookie stores the authcookie (essentially the password) used to
|
||||
// authenticate the Session.
|
||||
func (h *Session) SetAuthCookie(a []byte) {
|
||||
h.authCookie = a
|
||||
}
|
||||
|
||||
// ClearAuthCookie attempts to scrub the Session's stored authcookie.
|
||||
//
|
||||
// This should of course be called as soon as possible after authentication
|
||||
// and it is no longer required.
|
||||
func (h *Session) ClearAuthCookie() {
|
||||
for i := range h.authCookie {
|
||||
h.authCookie[i] = 0
|
||||
}
|
||||
runtime.GC()
|
||||
}
|
||||
|
||||
// Status returns the (current) Session status code.
|
||||
//
|
||||
// This usually corresponds to a UNIX shell exit code, but
|
||||
// extended codes are returns at times to indicate internal errors.
|
||||
func (h Session) Status() uint32 {
|
||||
return h.status
|
||||
}
|
||||
|
||||
// SetStatus stores the current Session status code.
|
||||
func (h *Session) SetStatus(s uint32) {
|
||||
h.status = s
|
||||
}
|
||||
|
||||
// NewSession returns a new Session record.
|
||||
func NewSession(op, who, connhost, ttype, cmd, authcookie []byte, status uint32) *Session {
|
||||
return &Session{
|
||||
op: op,
|
||||
who: who,
|
||||
connhost: connhost,
|
||||
termtype: ttype,
|
||||
cmd: cmd,
|
||||
authCookie: authcookie,
|
||||
status: status}
|
||||
}
|
||||
30
session_test.go
Normal file
30
session_test.go
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
package xs
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func _newMockSession() (s *Session) {
|
||||
s = &Session{op: []byte("A"),
|
||||
who: []byte("johndoe"),
|
||||
connhost: []byte("host"),
|
||||
termtype: []byte("vt100"),
|
||||
cmd: []byte("/bin/false"),
|
||||
authCookie: []byte("authcookie"),
|
||||
status: 0}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestSessionAuthCookieShowTrue(t *testing.T) {
|
||||
sess := _newMockSession()
|
||||
if string(sess.AuthCookie(true)) != string(sess.authCookie) {
|
||||
t.Fatal("Failed to return unredacted authcookie on request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionAuthCookieShowFalse(t *testing.T) {
|
||||
sess := _newMockSession()
|
||||
if string(sess.AuthCookie(false)) != string("**REDACTED**") {
|
||||
t.Fatal("Failed to return redacted authcookie on request")
|
||||
}
|
||||
}
|
||||
17
spinsult/Makefile
Normal file
17
spinsult/Makefile
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
.PHONY: info clean lib
|
||||
|
||||
all: lib
|
||||
|
||||
clean:
|
||||
go clean .
|
||||
|
||||
lib: info
|
||||
go install .
|
||||
|
||||
ifneq ($(MSYSTEM),)
|
||||
info:
|
||||
@echo "Building for Windows (MSYS)"
|
||||
else
|
||||
info:
|
||||
@echo "Building for Linux"
|
||||
endif
|
||||
128
termmode_bsd.go
Normal file
128
termmode_bsd.go
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
// +build freebsd
|
||||
|
||||
package xs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"unsafe"
|
||||
|
||||
unix "golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
/* -------------
|
||||
* minimal terminal APIs brought in from ssh/terminal
|
||||
* (they have no real business being there as they aren't specific to
|
||||
* ssh, but as of Go v1.10, late 2019, core go stdlib hasn't yet done
|
||||
* the planned terminal lib reorgs.)
|
||||
* ------------- */
|
||||
|
||||
// From github.com/golang/crypto/blob/master/ssh/terminal/util_linux.go
|
||||
const getTermios = unix.TIOCGETA
|
||||
const setTermios = unix.TIOCSETA
|
||||
|
||||
// From github.com/golang/crypto/blob/master/ssh/terminal/util.go
|
||||
|
||||
// State contains the state of a terminal.
|
||||
type State struct {
|
||||
termios unix.Termios
|
||||
}
|
||||
|
||||
// MakeRaw put the terminal connected to the given file descriptor into raw
|
||||
// mode and returns the previous state of the terminal so that it can be
|
||||
// restored.
|
||||
func MakeRaw(fd uintptr) (*State, error) {
|
||||
var oldState State
|
||||
if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newState := oldState.termios
|
||||
newState.Iflag &^= (unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON)
|
||||
newState.Oflag &^= unix.OPOST
|
||||
newState.Lflag &^= (unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN)
|
||||
newState.Cflag &^= (unix.CSIZE | unix.PARENB)
|
||||
newState.Cflag |= unix.CS8
|
||||
newState.Cc[unix.VMIN] = 1
|
||||
newState.Cc[unix.VTIME] = 0
|
||||
|
||||
if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oldState, nil
|
||||
}
|
||||
|
||||
// Restore restores the terminal connected to the given file descriptor to a
|
||||
// previous state.
|
||||
func Restore(fd uintptr, state *State) error {
|
||||
if state != nil {
|
||||
if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(state))); err != 0 {
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
return errors.New("nil State")
|
||||
}
|
||||
}
|
||||
|
||||
// ReadPassword reads a line of input from a terminal without local echo. This
|
||||
// is commonly used for inputting passwords and other sensitive data. The slice
|
||||
// returned does not include the \n.
|
||||
func ReadPassword(fd uintptr) ([]byte, error) {
|
||||
var oldState State
|
||||
if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newState := oldState.termios
|
||||
newState.Lflag &^= unix.ECHO
|
||||
newState.Lflag |= unix.ICANON | unix.ISIG
|
||||
newState.Iflag |= unix.ICRNL
|
||||
if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
unix.Syscall(unix.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&oldState.termios)))
|
||||
}()
|
||||
|
||||
return readPasswordLine(passwordReader(fd))
|
||||
}
|
||||
|
||||
// passwordReader is an io.Reader that reads from a specific file descriptor.
|
||||
type passwordReader int
|
||||
|
||||
func (r passwordReader) Read(buf []byte) (int, error) {
|
||||
return unix.Read(int(r), buf)
|
||||
}
|
||||
|
||||
// readPasswordLine reads from reader until it finds \n or io.EOF.
|
||||
// The slice returned does not include the \n.
|
||||
// readPasswordLine also ignores any \r it finds.
|
||||
func readPasswordLine(reader io.Reader) ([]byte, error) {
|
||||
var buf [1]byte
|
||||
var ret []byte
|
||||
|
||||
for {
|
||||
n, err := reader.Read(buf[:])
|
||||
if n > 0 {
|
||||
switch buf[0] {
|
||||
case '\n':
|
||||
return ret, nil
|
||||
case '\r':
|
||||
// remove \r from passwords on Windows
|
||||
default:
|
||||
ret = append(ret, buf[0])
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
if err == io.EOF && len(ret) > 0 {
|
||||
return ret, nil
|
||||
}
|
||||
return ret, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
// +build linux
|
||||
|
||||
package hkexsh
|
||||
package xs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
unix "golang.org/x/sys/unix"
|
||||
|
|
@ -11,7 +12,7 @@ import (
|
|||
/* -------------
|
||||
* minimal terminal APIs brought in from ssh/terminal
|
||||
* (they have no real business being there as they aren't specific to
|
||||
* ssh, but as of Go v1.10, early 2018, core go stdlib hasn't yet done
|
||||
* ssh, but as of Go v1.10, late 2019, core go stdlib hasn't yet done
|
||||
* the planned terminal lib reorgs.)
|
||||
* ------------- */
|
||||
|
||||
|
|
@ -20,6 +21,7 @@ const ioctlReadTermios = unix.TCGETS
|
|||
const ioctlWriteTermios = unix.TCSETS
|
||||
|
||||
// From github.com/golang/crypto/blob/master/ssh/terminal/util.go
|
||||
|
||||
// State contains the state of a terminal.
|
||||
type State struct {
|
||||
termios unix.Termios
|
||||
|
|
@ -28,8 +30,8 @@ type State struct {
|
|||
// MakeRaw put the terminal connected to the given file descriptor into raw
|
||||
// mode and returns the previous state of the terminal so that it can be
|
||||
// restored.
|
||||
func MakeRaw(fd int) (*State, error) {
|
||||
termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
|
||||
func MakeRaw(fd uintptr) (*State, error) {
|
||||
termios, err := unix.IoctlGetTermios(int(fd), ioctlReadTermios)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -45,7 +47,7 @@ func MakeRaw(fd int) (*State, error) {
|
|||
termios.Cflag |= unix.CS8
|
||||
termios.Cc[unix.VMIN] = 1
|
||||
termios.Cc[unix.VTIME] = 0
|
||||
if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, termios); err != nil {
|
||||
if err := unix.IoctlSetTermios(int(fd), ioctlWriteTermios, termios); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
|
@ -54,8 +56,8 @@ func MakeRaw(fd int) (*State, error) {
|
|||
|
||||
// GetState returns the current state of a terminal which may be useful to
|
||||
// restore the terminal after a signal.
|
||||
func GetState(fd int) (*State, error) {
|
||||
termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
|
||||
func GetState(fd uintptr) (*State, error) {
|
||||
termios, err := unix.IoctlGetTermios(int(fd), ioctlReadTermios)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -65,15 +67,19 @@ func GetState(fd int) (*State, error) {
|
|||
|
||||
// Restore restores the terminal connected to the given file descriptor to a
|
||||
// previous state.
|
||||
func Restore(fd int, state *State) error {
|
||||
return unix.IoctlSetTermios(fd, ioctlWriteTermios, &state.termios)
|
||||
func Restore(fd uintptr, state *State) error {
|
||||
if state != nil {
|
||||
return unix.IoctlSetTermios(int(fd), ioctlWriteTermios, &state.termios)
|
||||
} else {
|
||||
return errors.New("nil State")
|
||||
}
|
||||
}
|
||||
|
||||
// ReadPassword reads a line of input from a terminal without local echo. This
|
||||
// is commonly used for inputting passwords and other sensitive data. The slice
|
||||
// returned does not include the \n.
|
||||
func ReadPassword(fd int) ([]byte, error) {
|
||||
termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
|
||||
func ReadPassword(fd uintptr) ([]byte, error) {
|
||||
termios, err := unix.IoctlGetTermios(int(fd), ioctlReadTermios)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -82,12 +88,12 @@ func ReadPassword(fd int) ([]byte, error) {
|
|||
newState.Lflag &^= unix.ECHO
|
||||
newState.Lflag |= unix.ICANON | unix.ISIG
|
||||
newState.Iflag |= unix.ICRNL
|
||||
if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, &newState); err != nil {
|
||||
if err := unix.IoctlSetTermios(int(fd), ioctlWriteTermios, &newState); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
unix.IoctlSetTermios(fd, ioctlWriteTermios, termios)
|
||||
_ = unix.IoctlSetTermios(int(fd), ioctlWriteTermios, termios) // nolint: gosec
|
||||
}()
|
||||
|
||||
return readPasswordLine(passwordReader(fd))
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
// +build windows
|
||||
//
|
||||
|
||||
// Note the terminal manipulation functions herein are mostly stubs. They
|
||||
// don't really do anything and the hkexsh demo client depends on a wrapper
|
||||
// don't really do anything and the xs demo client depends on a wrapper
|
||||
// script using the 'stty' tool to actually set the proper mode for
|
||||
// password login and raw mode required, then restoring it upon logout/exit.
|
||||
//
|
||||
|
|
@ -12,7 +12,7 @@
|
|||
// here; the wrapper does the bare minimum to make the client workable
|
||||
// under MSYS+mintty which is what I use.
|
||||
|
||||
package hkexsh
|
||||
package xs
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
|
@ -27,7 +27,7 @@ type State struct {
|
|||
// MakeRaw put the terminal connected to the given file descriptor into raw
|
||||
// mode and returns the previous state of the terminal so that it can be
|
||||
// restored.
|
||||
func MakeRaw(fd int) (*State, error) {
|
||||
func MakeRaw(fd uintptr) (*State, error) {
|
||||
// This doesn't really work. The exec.Command() runs a sub-shell
|
||||
// so the stty mods don't affect the client process.
|
||||
cmd := exec.Command("stty", "-echo raw")
|
||||
|
|
@ -37,13 +37,13 @@ func MakeRaw(fd int) (*State, error) {
|
|||
|
||||
// GetState returns the current state of a terminal which may be useful to
|
||||
// restore the terminal after a signal.
|
||||
func GetState(fd int) (*State, error) {
|
||||
func GetState(fd uintptr) (*State, error) {
|
||||
return &State{}, nil
|
||||
}
|
||||
|
||||
// Restore restores the terminal connected to the given file descriptor to a
|
||||
// previous state.
|
||||
func Restore(fd int, state *State) error {
|
||||
func Restore(fd uintptr, state *State) error {
|
||||
cmd := exec.Command("stty", "echo cooked")
|
||||
cmd.Run()
|
||||
return nil
|
||||
|
|
@ -52,7 +52,7 @@ func Restore(fd int, state *State) error {
|
|||
// ReadPassword reads a line of input from a terminal without local echo. This
|
||||
// is commonly used for inputting passwords and other sensitive data. The slice
|
||||
// returned does not include the \n.
|
||||
func ReadPassword(fd int) ([]byte, error) {
|
||||
func ReadPassword(fd uintptr) ([]byte, error) {
|
||||
return readPasswordLine(passwordReader(fd))
|
||||
}
|
||||
|
||||
|
|
|
|||
BIN
viz_xs_dot.png
Normal file
BIN
viz_xs_dot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 675 KiB |
18
xs/Makefile
Normal file
18
xs/Makefile
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
.PHONY: clean all vis lint
|
||||
|
||||
EXTPKGS = bytes,errors,flag,fmt,internal,io,log,net,os,path,runtime,time,strings,sync,syscall,binary,encoding
|
||||
EXE = $(notdir $(shell pwd))
|
||||
|
||||
all:
|
||||
echo "BUILDOPTS:" $(BUILDOPTS)
|
||||
go build $(BUILDOPTS) .
|
||||
|
||||
clean:
|
||||
$(RM) $(EXE) $(EXE).exe
|
||||
|
||||
vis:
|
||||
go-callvis -file xs-vis -format png -ignore $(EXTPKGS) -group pkg,type .
|
||||
../fixup-gv.sh xs.go && cat xs-vis.gv | dot -Tpng -oxs-vis-fixedup.png
|
||||
|
||||
lint:
|
||||
-golangci-lint run
|
||||
|
|
@ -27,6 +27,13 @@ trap cleanup EXIT ERR
|
|||
cleanup() {
|
||||
stty sane
|
||||
}
|
||||
|
||||
stty -echo raw icrnl
|
||||
./hkexsh $@
|
||||
|
||||
me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"
|
||||
|
||||
if [ ${1}x == "-hx" ]; then
|
||||
_${me} -h
|
||||
else
|
||||
stty -echo raw icrnl
|
||||
_${me} $@
|
||||
fi
|
||||
|
||||
37
xs/termsize_unix.go
Normal file
37
xs/termsize_unix.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
// +build linux freebsd
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"blitter.com/go/xs/xsnet"
|
||||
)
|
||||
|
||||
// Handle pty resizes (notify server side)
|
||||
func handleTermResizes(conn *xsnet.Conn) {
|
||||
ch := make(chan os.Signal, 1)
|
||||
signal.Notify(ch, syscall.SIGWINCH)
|
||||
wg.Add(1)
|
||||
// #gv:s/label=\"handleTermResizes\$1\"/label=\"resizeHandler\"/
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
for range ch {
|
||||
// Query client's term size so we can communicate it to server
|
||||
// pty after interactive session starts
|
||||
cols, rows, err := GetSize()
|
||||
log.Printf("[rows %v cols %v]\n", rows, cols)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
termSzPacket := fmt.Sprintf("%d %d", rows, cols)
|
||||
conn.WritePacket([]byte(termSzPacket), xsnet.CSOTermSize) // nolint: errcheck,gosec
|
||||
}
|
||||
}()
|
||||
ch <- syscall.SIGWINCH // Initial resize.
|
||||
}
|
||||
65
xs/termsize_windows.go
Normal file
65
xs/termsize_windows.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
// +build windows
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"blitter.com/go/xs/xsnet"
|
||||
)
|
||||
|
||||
// Handle pty resizes (notify server side)
|
||||
func handleTermResizes(conn *xsnet.Conn) {
|
||||
var hasStty bool
|
||||
curCols, curRows := 0, 0
|
||||
_, _, err := GetSize()
|
||||
// The above may fail if user doesn't have msys 'stty' util
|
||||
// in PATH. GetSize() will log.Error() once here
|
||||
if err != nil {
|
||||
fmt.Println("[1st GetSize:", err, "]")
|
||||
hasStty = false
|
||||
} else {
|
||||
hasStty = true
|
||||
}
|
||||
|
||||
ch := make(chan bool, 1)
|
||||
|
||||
if hasStty {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
ch <- true
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
rows := 0
|
||||
cols := 0
|
||||
for range ch {
|
||||
// Query client's term size so we can communicate it to server
|
||||
// pty after interactive session starts
|
||||
cols, rows, err = GetSize()
|
||||
if err == nil {
|
||||
} else {
|
||||
fmt.Println("[GetSize:", err, "]")
|
||||
}
|
||||
if (curRows != rows) || (curCols != curCols) {
|
||||
curRows = rows
|
||||
curCols = cols
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
termSzPacket := fmt.Sprintf("%d %d", curRows, curCols)
|
||||
conn.WritePacket([]byte(termSzPacket), xsnet.CSOTermSize)
|
||||
}
|
||||
}
|
||||
}()
|
||||
ch <- true // Initial resize
|
||||
}
|
||||
BIN
xs/xs-vis-fixedup.png
Normal file
BIN
xs/xs-vis-fixedup.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.1 MiB |
549
xs/xs-vis.gv
Executable file
549
xs/xs-vis.gv
Executable file
|
|
@ -0,0 +1,549 @@
|
|||
digraph gocallvis {
|
||||
label="blitter.com/go/xs/xs";
|
||||
labeljust="l";
|
||||
fontname="Arial";
|
||||
fontsize="14";
|
||||
rankdir="LR";
|
||||
bgcolor="lightgray";
|
||||
style="solid";
|
||||
penwidth="0.5";
|
||||
pad="0.0";
|
||||
nodesep="0.35";
|
||||
|
||||
node [shape="ellipse" style="filled" fillcolor="honeydew" fontname="Verdana" penwidth="1.0" margin="0.05,0.0"];
|
||||
edge [minlen="2"]
|
||||
|
||||
subgraph "cluster_focus" {
|
||||
bgcolor="#e6ecfa";
|
||||
label="main";
|
||||
labelloc="t";
|
||||
labeljust="c";
|
||||
fontsize="18";
|
||||
|
||||
"blitter.com/go/xs/xs.reqTunnel" [ fillcolor="lightblue" label="reqTunnel" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.launchTuns" [ label="launchTuns" penwidth="0.5" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xs.main$3" [ fillcolor="lightblue" label="main$3" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.doCopyMode" [ fillcolor="lightblue" label="doCopyMode" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer" [ fillcolor="lightblue" label="copyBuffer" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer$1" [ label="copyBuffer$1" style="dotted,filled" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer$2" [ label="copyBuffer$2" style="dotted,filled" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer$3" [ fillcolor="lightblue" label="copyBuffer$3" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.Copy" [ label="Copy" penwidth="1.5" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" [ fillcolor="lightblue" label="shellRemoteToStdin" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1$1" [ fillcolor="lightblue" label="doShellMode$1$1" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.exitWithStatus" [ fillcolor="lightblue" label="exitWithStatus" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.doShellMode" [ label="doShellMode" penwidth="0.5" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xs.handleTermResizes$1" [ fillcolor="lightblue" label="handleTermResizes$1" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.GetSize" [ fillcolor="lightblue" label="GetSize" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/xs.handleTermResizes" [ label="handleTermResizes" penwidth="0.5" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$2$1" [ fillcolor="lightblue" label="doShellMode$2$1" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$2" [ fillcolor="lightblue" label="shellStdinToRemote" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" [ fillcolor="lightblue" label="sendSessionParams" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.main" [ label="main" penwidth="0.5" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xs.parseNonSwitchArgs" [ fillcolor="lightblue" label="parseNonSwitchArgs" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.main$1" [ fillcolor="lightblue" label="deferRestore" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.main$2" [ fillcolor="lightblue" label="deferCloseChaff" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xs.rejectUserMsg" [ fillcolor="lightblue" label="rejectUserMsg" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.usageShell" [ fillcolor="lightblue" label="usageShell" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xs.usageCp" [ label="usageCp" penwidth="0.5" fillcolor="lightblue" ]
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs" {
|
||||
penwidth="0.8";
|
||||
style="filled";
|
||||
rank="sink";
|
||||
tooltip="package: blitter.com/go/xs";
|
||||
fontsize="16";
|
||||
fillcolor="lightyellow";
|
||||
fontname="bold";
|
||||
label="[xs]";
|
||||
URL="/?f=blitter.com/go/xs";
|
||||
|
||||
"blitter.com/go/xs.Restore" [ fillcolor="moccasin" label="Restore" penwidth="1.5" ]
|
||||
"blitter.com/go/xs.MakeRaw" [ penwidth="1.5" fillcolor="moccasin" label="MakeRaw" ]
|
||||
"blitter.com/go/xs.ReadPassword" [ fillcolor="moccasin" label="ReadPassword" penwidth="1.5" ]
|
||||
"blitter.com/go/xs.NewSession" [ fillcolor="moccasin" label="NewSession" penwidth="1.5" ]
|
||||
|
||||
subgraph "cluster_*blitter.com/go/xs.Session" {
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(*Session)";
|
||||
tooltip="type: *blitter.com/go/xs.Session";
|
||||
penwidth="0.5";
|
||||
|
||||
"(*blitter.com/go/xs.Session).SetStatus" [ fillcolor="moccasin" label="SetStatus" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs.Session" {
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(Session)";
|
||||
tooltip="type: blitter.com/go/xs.Session";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
|
||||
"(blitter.com/go/xs.Session).Cmd" [ fillcolor="moccasin" label="Cmd" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs.Session).Status" [ penwidth="1.5" fillcolor="moccasin" label="Status" ]
|
||||
"(blitter.com/go/xs.Session).Op" [ fillcolor="moccasin" label="Op" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs.Session).Who" [ fillcolor="moccasin" label="Who" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs.Session).ConnHost" [ fillcolor="moccasin" label="ConnHost" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs.Session).TermType" [ fillcolor="moccasin" label="TermType" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs.Session).AuthCookie" [ label="AuthCookie" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/logger" {
|
||||
fontsize="16";
|
||||
URL="/?f=blitter.com/go/xs/logger";
|
||||
penwidth="0.8";
|
||||
style="filled";
|
||||
fillcolor="lightyellow";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
label="[logger]";
|
||||
tooltip="package: blitter.com/go/xs/logger";
|
||||
|
||||
"blitter.com/go/xs/logger.LogDebug" [ fillcolor="moccasin" label="LogDebug" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/logger.New" [ fillcolor="moccasin" label="New" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/spinsult" {
|
||||
fillcolor="lightyellow";
|
||||
fontname="bold";
|
||||
label="[spinsult]";
|
||||
URL="/?f=blitter.com/go/xs/spinsult";
|
||||
tooltip="package: blitter.com/go/xs/spinsult";
|
||||
penwidth="0.8";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
rank="sink";
|
||||
|
||||
"blitter.com/go/xs/spinsult.GetSentence" [ fillcolor="moccasin" label="GetSentence" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/xsnet" {
|
||||
penwidth="0.8";
|
||||
fillcolor="lightyellow";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
URL="/?f=blitter.com/go/xs/xsnet";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
label="[xsnet]";
|
||||
tooltip="package: blitter.com/go/xs/xsnet";
|
||||
|
||||
"blitter.com/go/xs/xsnet.Init" [ fillcolor="moccasin" label="Init" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/xsnet.Dial" [ label="Dial" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
subgraph "cluster_*blitter.com/go/xs/xsnet.Conn" {
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(*Conn)";
|
||||
tooltip="type: *blitter.com/go/xs/xsnet.Conn";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
|
||||
"(*blitter.com/go/xs/xsnet.Conn).WritePacket" [ penwidth="1.5" fillcolor="moccasin" label="WritePacket" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).SetStatus" [ fillcolor="moccasin" label="SetStatus" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).Close" [ penwidth="1.5" fillcolor="moccasin" label="Close" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).SetupChaff" [ penwidth="1.5" fillcolor="moccasin" label="SetupChaff" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).EnableChaff" [ fillcolor="moccasin" label="EnableChaff" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).DisableChaff" [ fillcolor="moccasin" label="DisableChaff" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).ShutdownChaff" [ fillcolor="moccasin" label="ShutdownChaff" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/xsnet.Conn" {
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(Conn)";
|
||||
tooltip="type: blitter.com/go/xs/xsnet.Conn";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
|
||||
"(blitter.com/go/xs/xsnet.Conn).Read" [ label="Read" penwidth="1.5" fillcolor="moccasin" ]
|
||||
"(blitter.com/go/xs/xsnet.Conn).GetStatus" [ fillcolor="moccasin" label="GetStatus" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs/xsnet.Conn).Write" [ label="Write" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_compress/flate" {
|
||||
fontsize="16";
|
||||
fillcolor="#E0FFE1";
|
||||
label="[compress/flate]";
|
||||
URL="/?f=compress/flate";
|
||||
penwidth="0.8";
|
||||
style="filled";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
tooltip="package: compress/flate";
|
||||
|
||||
|
||||
subgraph "cluster_compress/flate.CorruptInputError" {
|
||||
tooltip="type: compress/flate.CorruptInputError";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(CorruptInputError)";
|
||||
|
||||
"(compress/flate.CorruptInputError).Error" [ penwidth="1.5" fillcolor="#adedad" label="Error" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_compress/flate.InternalError" {
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(InternalError)";
|
||||
tooltip="type: compress/flate.InternalError";
|
||||
penwidth="0.5";
|
||||
|
||||
"(compress/flate.InternalError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_context" {
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
penwidth="0.8";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
label="[context]";
|
||||
URL="/?f=context";
|
||||
tooltip="package: context";
|
||||
fillcolor="#E0FFE1";
|
||||
|
||||
|
||||
subgraph "cluster_context.deadlineExceededError" {
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(deadlineExceededError)";
|
||||
tooltip="type: context.deadlineExceededError";
|
||||
penwidth="0.5";
|
||||
|
||||
"(context.deadlineExceededError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/aes" {
|
||||
style="filled";
|
||||
fillcolor="#E0FFE1";
|
||||
rank="sink";
|
||||
label="[crypto/aes]";
|
||||
penwidth="0.8";
|
||||
fontsize="16";
|
||||
fontname="bold";
|
||||
URL="/?f=crypto/aes";
|
||||
tooltip="package: crypto/aes";
|
||||
|
||||
|
||||
subgraph "cluster_crypto/aes.KeySizeError" {
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(KeySizeError)";
|
||||
tooltip="type: crypto/aes.KeySizeError";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
|
||||
"(crypto/aes.KeySizeError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/tls" {
|
||||
tooltip="package: crypto/tls";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
label="[crypto/tls]";
|
||||
URL="/?f=crypto/tls";
|
||||
penwidth="0.8";
|
||||
fillcolor="#E0FFE1";
|
||||
|
||||
|
||||
subgraph "cluster_crypto/tls.RecordHeaderError" {
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(RecordHeaderError)";
|
||||
tooltip="type: crypto/tls.RecordHeaderError";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
|
||||
"(crypto/tls.RecordHeaderError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/tls.alert" {
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(alert)";
|
||||
tooltip="type: crypto/tls.alert";
|
||||
|
||||
"(crypto/tls.alert).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/x509" {
|
||||
penwidth="0.8";
|
||||
tooltip="package: crypto/x509";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
fillcolor="#E0FFE1";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
label="[crypto/x509]";
|
||||
URL="/?f=crypto/x509";
|
||||
|
||||
|
||||
subgraph "cluster_crypto/x509.CertificateInvalidError" {
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(CertificateInvalidError)";
|
||||
tooltip="type: crypto/x509.CertificateInvalidError";
|
||||
|
||||
"(crypto/x509.CertificateInvalidError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/x509.HostnameError" {
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(HostnameError)";
|
||||
tooltip="type: crypto/x509.HostnameError";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
|
||||
"(crypto/x509.HostnameError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/x509.SystemRootsError" {
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(SystemRootsError)";
|
||||
tooltip="type: crypto/x509.SystemRootsError";
|
||||
penwidth="0.5";
|
||||
|
||||
"(crypto/x509.SystemRootsError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/x509.UnhandledCriticalExtension" {
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(UnhandledCriticalExtension)";
|
||||
tooltip="type: crypto/x509.UnhandledCriticalExtension";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
|
||||
"(crypto/x509.UnhandledCriticalExtension).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_crypto/x509.UnknownAuthorityError" {
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(UnknownAuthorityError)";
|
||||
tooltip="type: crypto/x509.UnknownAuthorityError";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
|
||||
"(crypto/x509.UnknownAuthorityError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_github.com/mattn/go-isatty" {
|
||||
fontname="bold";
|
||||
penwidth="0.8";
|
||||
fillcolor="lightyellow";
|
||||
rank="sink";
|
||||
label="[isatty]";
|
||||
URL="/?f=github.com/mattn/go-isatty";
|
||||
tooltip="package: github.com/mattn/go-isatty";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
|
||||
"github.com/mattn/go-isatty.IsTerminal" [ label="IsTerminal" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_github.com/pkg/errors" {
|
||||
style="filled";
|
||||
fillcolor="lightyellow";
|
||||
URL="/?f=github.com/pkg/errors";
|
||||
rank="sink";
|
||||
label="[errors]";
|
||||
tooltip="package: github.com/pkg/errors";
|
||||
penwidth="0.8";
|
||||
fontsize="16";
|
||||
fontname="bold";
|
||||
|
||||
|
||||
subgraph "cluster_*github.com/pkg/errors.fundamental" {
|
||||
label="(*fundamental)";
|
||||
tooltip="type: *github.com/pkg/errors.fundamental";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
|
||||
"(*github.com/pkg/errors.fundamental).Error" [ penwidth="1.5" fillcolor="moccasin" label="Error" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_math/rand" {
|
||||
penwidth="0.8";
|
||||
fillcolor="#E0FFE1";
|
||||
rank="sink";
|
||||
URL="/?f=math/rand";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
fontname="bold";
|
||||
label="[math/rand]";
|
||||
tooltip="package: math/rand";
|
||||
|
||||
"math/rand.Intn" [ fillcolor="#adedad" label="Intn" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
"blitter.com/go/xs/xs.reqTunnel" -> "blitter.com/go/xs/logger.LogDebug" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.reqTunnel" -> "(*blitter.com/go/xs/xsnet.Conn).WritePacket" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.launchTuns" -> "blitter.com/go/xs/xs.reqTunnel" [ ]
|
||||
"blitter.com/go/xs/xs.main$3" -> "math/rand.Intn" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main$3" -> "(*blitter.com/go/xs/xsnet.Conn).WritePacket" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doCopyMode" -> "(blitter.com/go/xs.Session).Cmd" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doCopyMode" -> "(*blitter.com/go/xs/xsnet.Conn).WritePacket" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doCopyMode" -> "(blitter.com/go/xs/xsnet.Conn).Read" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doCopyMode" -> "(*blitter.com/go/xs/xsnet.Conn).SetStatus" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doCopyMode" -> "(blitter.com/go/xs/xsnet.Conn).GetStatus" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer" -> "(blitter.com/go/xs/xsnet.Conn).Write" [ color="saddlebrown" style="dashed" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer" -> "blitter.com/go/xs/xs.copyBuffer$1" [ style="dashed" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer" -> "blitter.com/go/xs/xs.copyBuffer$2" [ style="dashed" ]
|
||||
"blitter.com/go/xs/xs.copyBuffer" -> "blitter.com/go/xs/xs.copyBuffer$3" [ style="dashed" ]
|
||||
"blitter.com/go/xs/xs.Copy" -> "blitter.com/go/xs/xs.copyBuffer" [ ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "blitter.com/go/xs/xs.doShellMode$1$1" [ arrowhead="normalnoneodiamond" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "blitter.com/go/xs.Restore" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(blitter.com/go/xs/xsnet.Conn).GetStatus" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(*blitter.com/go/xs.Session).SetStatus" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(blitter.com/go/xs.Session).Status" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "blitter.com/go/xs/xs.exitWithStatus" [ ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/x509.CertificateInvalidError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/aes.KeySizeError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/x509.HostnameError).Error" [ color="saddlebrown" style="dashed" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/x509.UnhandledCriticalExtension).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(context.deadlineExceededError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(compress/flate.CorruptInputError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/tls.RecordHeaderError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/x509.UnknownAuthorityError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/x509.SystemRootsError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(compress/flate.InternalError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(crypto/tls.alert).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$1" -> "(*github.com/pkg/errors.fundamental).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode" -> "blitter.com/go/xs/xs.doShellMode$1" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xs.handleTermResizes$1" -> "blitter.com/go/xs/xs.GetSize" [ ]
|
||||
"blitter.com/go/xs/xs.handleTermResizes$1" -> "(*blitter.com/go/xs/xsnet.Conn).WritePacket" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.handleTermResizes" -> "blitter.com/go/xs/xs.handleTermResizes$1" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xs.doShellMode" -> "blitter.com/go/xs/xs.handleTermResizes" [ ]
|
||||
"blitter.com/go/xs/xs.doShellMode$2$1" -> "blitter.com/go/xs/xs.Copy" [ ]
|
||||
"blitter.com/go/xs/xs.doShellMode$2" -> "blitter.com/go/xs/xs.doShellMode$2$1" [ ]
|
||||
"blitter.com/go/xs/xs.doShellMode$2" -> "blitter.com/go/xs.Restore" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.doShellMode$2" -> "blitter.com/go/xs/xs.exitWithStatus" [ ]
|
||||
"blitter.com/go/xs/xs.doShellMode" -> "blitter.com/go/xs/xs.doShellMode$2" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" -> "(blitter.com/go/xs.Session).Op" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" -> "(blitter.com/go/xs.Session).Who" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" -> "(blitter.com/go/xs.Session).ConnHost" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" -> "(blitter.com/go/xs.Session).TermType" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" -> "(blitter.com/go/xs.Session).Cmd" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" -> "(blitter.com/go/xs.Session).AuthCookie" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.sendSessionParams" -> "(blitter.com/go/xs/xsnet.Conn).Write" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.parseNonSwitchArgs" [ ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.main$1" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.exitWithStatus" [ ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/logger.New" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xsnet.Init" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xsnet.Dial" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "(*blitter.com/go/xs/xsnet.Conn).Close" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "github.com/mattn/go-isatty.IsTerminal" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs.MakeRaw" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main$2" -> "blitter.com/go/xs.Restore" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.main$2" [ arrowhead="normalnoneodiamond" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs.ReadPassword" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs.NewSession" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.sendSessionParams" [ ]
|
||||
"blitter.com/go/xs/xs.main" -> "(blitter.com/go/xs/xsnet.Conn).Read" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "(*blitter.com/go/xs.Session).SetStatus" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.rejectUserMsg" -> "blitter.com/go/xs/spinsult.GetSentence" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.rejectUserMsg" [ ]
|
||||
"blitter.com/go/xs/xs.main" -> "(*blitter.com/go/xs/xsnet.Conn).SetupChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "(*blitter.com/go/xs/xsnet.Conn).EnableChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "(*blitter.com/go/xs/xsnet.Conn).DisableChaff" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "(*blitter.com/go/xs/xsnet.Conn).ShutdownChaff" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.main$3" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.launchTuns" [ ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.doShellMode" [ ]
|
||||
"blitter.com/go/xs/xs.main" -> "(blitter.com/go/xs.Session).Status" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.doCopyMode" [ ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs.Restore" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.usageShell" [ style="dashed" ]
|
||||
"blitter.com/go/xs/xs.main" -> "blitter.com/go/xs/xs.usageCp" [ style="dashed" ]
|
||||
}
|
||||
BIN
xs/xs_seq.png
Normal file
BIN
xs/xs_seq.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 67 KiB |
39
xsd.initrc
Executable file
39
xsd.initrc
Executable file
|
|
@ -0,0 +1,39 @@
|
|||
#!/sbin/openrc-run
|
||||
|
||||
SVCNAME=xsd
|
||||
XSD_PIDFILE=/var/run/xsd.pid
|
||||
XSD_USER=root
|
||||
XSD_HOME=/var/run
|
||||
INST_PREFIX=/usr/local
|
||||
COMMAND=$INST_PREFIX/sbin/xsd
|
||||
ARGS="-L"
|
||||
|
||||
depend() {
|
||||
need net
|
||||
use dns logger
|
||||
}
|
||||
|
||||
checkconfig() {
|
||||
if [ ! -f "$COMMAND" ] ; then
|
||||
eerror "$COMMAND not installed" || return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
start() {
|
||||
checkconfig || return 1
|
||||
|
||||
ebegin "Starting ${SVCNAME}"
|
||||
start-stop-daemon \
|
||||
-d ${XSD_HOME} \
|
||||
--make-pidfile --pidfile ${XSD_PIDFILE} \
|
||||
--start --quiet --background \
|
||||
--exec "${COMMAND}" -- "${ARGS}"
|
||||
eend $?
|
||||
}
|
||||
|
||||
stop() {
|
||||
ebegin "Stopping ${SVCNAME}"
|
||||
start-stop-daemon --stop --quiet --pidfile $XSD_PIDFILE
|
||||
eend $?
|
||||
}
|
||||
162
xsd.sysvrc
Executable file
162
xsd.sysvrc
Executable file
|
|
@ -0,0 +1,162 @@
|
|||
#! /bin/sh
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: xsd
|
||||
# Required-Start: $remote_fs $syslog
|
||||
# Required-Stop: $remote_fs $syslog
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop:
|
||||
# Short-Description: eXperimental Shell Daemon
|
||||
### END INIT INFO
|
||||
|
||||
set -e
|
||||
|
||||
# /etc/init.d/xsd: start and stop the eXperimental "secure" Shell Daemon
|
||||
|
||||
test -x /usr/local/sbin/xsd || exit 0
|
||||
( /usr/local/sbin/xsd -h 2>&1 | grep -q chaff ) 2>/dev/null || exit 0
|
||||
|
||||
umask 022
|
||||
|
||||
#if test -f /etc/default/ssh; then
|
||||
# . /etc/default/ssh
|
||||
#fi
|
||||
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
if [ -n "$2" ]; then
|
||||
XSD_OPTS="$XSD_OPTS $2"
|
||||
fi
|
||||
|
||||
# Are we running from init?
|
||||
run_by_init() {
|
||||
([ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S ]
|
||||
}
|
||||
|
||||
check_for_no_start() {
|
||||
# forget it if we're trying to start, and /etc/xsd_not_to_be_run exists
|
||||
if [ -e /etc/xsd_not_to_be_run ]; then
|
||||
if [ "$1" = log_end_msg ]; then
|
||||
log_end_msg 0 || true
|
||||
fi
|
||||
if ! run_by_init; then
|
||||
log_action_msg "eXperimental Shell Daemon not in use (/etc/xsd_not_to_be_run)" || true
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
}
|
||||
|
||||
check_dev_null() {
|
||||
if [ ! -c /dev/null ]; then
|
||||
if [ "$1" = log_end_msg ]; then
|
||||
log_end_msg 1 || true
|
||||
fi
|
||||
if ! run_by_init; then
|
||||
log_action_msg "/dev/null is not a character device!" || true
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
#check_privsep_dir() {
|
||||
# # Create the PrivSep empty dir if necessary
|
||||
# if [ ! -d /run/sshd ]; then
|
||||
# mkdir /run/sshd
|
||||
# chmod 0755 /run/sshd
|
||||
# fi
|
||||
#}
|
||||
|
||||
#check_config() {
|
||||
# if [ ! -e /etc/xsd_not_to_be_run ]; then
|
||||
# /usr/local/sbin/xsd $XSD_OPTS -t || exit 1
|
||||
# fi
|
||||
#}
|
||||
|
||||
export PATH="${PATH:+$PATH:}/usr/local/sbin:/usr/sbin:/sbin"
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
#check_privsep_dir
|
||||
check_for_no_start
|
||||
check_dev_null
|
||||
log_daemon_msg "Starting eXperimental Shell Daemon" "xsd" || true
|
||||
if start-stop-daemon --start -b --quiet --oknodo --chuid 0:0 --exec /usr/local/sbin/xsd -- $XSD_OPTS; then
|
||||
log_end_msg 0 || true
|
||||
else
|
||||
log_end_msg 1 || true
|
||||
fi
|
||||
;;
|
||||
stop)
|
||||
log_daemon_msg "Stopping eXperimental Shell Daemon" "xsd" || true
|
||||
if start-stop-daemon --stop --quiet --oknodo --exec /usr/local/sbin/xsd; then
|
||||
log_end_msg 0 || true
|
||||
else
|
||||
log_end_msg 1 || true
|
||||
fi
|
||||
;;
|
||||
|
||||
reload|force-reload)
|
||||
check_for_no_start
|
||||
#check_config
|
||||
log_daemon_msg "Reloading eXperimental Shell Daemon's configuration" "xsd" || true
|
||||
if start-stop-daemon --stop --signal 1 --quiet --oknodo --exec /usr/local/sbin/xsd; then
|
||||
log_end_msg 0 || true
|
||||
else
|
||||
log_end_msg 1 || true
|
||||
fi
|
||||
;;
|
||||
|
||||
restart)
|
||||
#check_privsep_dir
|
||||
#check_config
|
||||
log_daemon_msg "Restarting eXperimental Shell Daemon" "xsd" || true
|
||||
start-stop-daemon --stop --quiet --oknodo --retry 30 --exec /usr/local/sbin/xsd
|
||||
check_for_no_start log_end_msg
|
||||
check_dev_null log_end_msg
|
||||
if start-stop-daemon --start -b --quiet --oknodo --chuid 0:0 --exec /usr/local/sbin/xsd -- $XSD_OPTS; then
|
||||
log_end_msg 0 || true
|
||||
else
|
||||
log_end_msg 1 || true
|
||||
fi
|
||||
;;
|
||||
|
||||
try-restart)
|
||||
#check_privsep_dir
|
||||
#check_config
|
||||
log_daemon_msg "Restarting eXperimental Shell Daemon" "xsd" || true
|
||||
RET=0
|
||||
start-stop-daemon --stop --quiet --retry 30 --exec /usr/local/sbin/xsd || RET="$?"
|
||||
case $RET in
|
||||
0)
|
||||
# old daemon stopped
|
||||
check_for_no_start log_end_msg
|
||||
check_dev_null log_end_msg
|
||||
if start-stop-daemon --start -b --quiet --oknodo --chuid 0:0 --exec /usr/local/sbin/xsd -- $XSD_OPTS; then
|
||||
log_end_msg 0 || true
|
||||
else
|
||||
log_end_msg 1 || true
|
||||
fi
|
||||
;;
|
||||
1)
|
||||
# daemon not running
|
||||
log_progress_msg "(not running)" || true
|
||||
log_end_msg 0 || true
|
||||
;;
|
||||
*)
|
||||
# failed to stop
|
||||
log_progress_msg "(failed to stop)" || true
|
||||
log_end_msg 1 || true
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
|
||||
status)
|
||||
status_of_proc -p /run/xsd.pid /usr/local/sbin/xsd xsd && exit 0 || exit $?
|
||||
;;
|
||||
|
||||
*)
|
||||
log_action_msg "Usage: /etc/init.d/xsd {start|stop|reload|force-reload|restart|try-restart|status}" || true
|
||||
exit 1
|
||||
esac
|
||||
|
||||
exit 0
|
||||
18
xsd/Makefile
Normal file
18
xsd/Makefile
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
.PHONY: clean all vis lint
|
||||
|
||||
EXTPKGS = binary,bytes,crypto,encoding,errors,flag,fmt,internal,io,log,net,os,path,runtime,time,strings,sync,syscall
|
||||
EXE = $(notdir $(shell pwd))
|
||||
|
||||
all:
|
||||
go build $(BUILDOPTS) .
|
||||
|
||||
clean:
|
||||
$(RM) $(EXE) $(EXE).exe
|
||||
|
||||
vis:
|
||||
go-callvis -file xsd-vis -format png -ignore $(EXTPKGS) -group pkg,type .
|
||||
../fixup-gv.sh xsd.go && cat xsd-vis.gv | dot -Tpng -oxsd-vis-fixedup.png
|
||||
|
||||
lint:
|
||||
-golangci-lint run
|
||||
|
||||
BIN
xsd/hkexshd-vis.png
Normal file
BIN
xsd/hkexshd-vis.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 581 KiB |
BIN
xsd/xsd-vis-fixedup.png
Normal file
BIN
xsd/xsd-vis-fixedup.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 782 KiB |
347
xsd/xsd-vis.gv
Executable file
347
xsd/xsd-vis.gv
Executable file
|
|
@ -0,0 +1,347 @@
|
|||
digraph gocallvis {
|
||||
label="blitter.com/go/xs/xsd";
|
||||
labeljust="l";
|
||||
fontname="Arial";
|
||||
fontsize="14";
|
||||
rankdir="LR";
|
||||
bgcolor="lightgray";
|
||||
style="solid";
|
||||
penwidth="0.5";
|
||||
pad="0.0";
|
||||
nodesep="0.35";
|
||||
|
||||
node [shape="ellipse" style="filled" fillcolor="honeydew" fontname="Verdana" penwidth="1.0" margin="0.05,0.0"];
|
||||
edge [minlen="2"]
|
||||
|
||||
subgraph "cluster_focus" {
|
||||
label="main";
|
||||
labelloc="t";
|
||||
labeljust="c";
|
||||
fontsize="18";
|
||||
bgcolor="#e6ecfa";
|
||||
|
||||
"blitter.com/go/xs/xsd.main$2" [ style="dotted,filled" fillcolor="lightblue" label="main$2" ]
|
||||
"blitter.com/go/xs/xsd.GenAuthToken" [ fillcolor="lightblue" label="GenAuthToken" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" [ fillcolor="lightblue" label="runShellAs" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$1" [ fillcolor="lightblue" label="deferPtmxClose" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xsd.ptsName" [ label="ptsName" penwidth="0.5" fillcolor="lightblue" ]
|
||||
"blitter.com/go/xs/xsd.ioctl" [ fillcolor="lightblue" label="ioctl" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$2" [ fillcolor="lightblue" label="termResizeWatcher" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$3" [ style="dotted,filled" fillcolor="lightblue" label="stdinToPtyWorker" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$4" [ style="dotted,filled" fillcolor="lightblue" label="deferChaffShutdown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$5" [ fillcolor="lightblue" label="ptyToStdoutWorker" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$6" [ fillcolor="lightblue" label="runShellAs$6" style="dotted,filled" ]
|
||||
"blitter.com/go/xs/xsd.runClientToServerCopyAs" [ fillcolor="lightblue" label="runClientToServerCopyAs" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xsd.runServerToClientCopyAs" [ fillcolor="lightblue" label="runServerToClientCopyAs" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xsd.main" [ fillcolor="lightblue" label="main" penwidth="0.5" ]
|
||||
"blitter.com/go/xs/xsd.main$1" [ fillcolor="lightblue" label="main$1" style="dotted,filled" ]
|
||||
|
||||
subgraph "cluster_blitter.com/go/goutmp" {
|
||||
URL="/?f=blitter.com/go/goutmp";
|
||||
tooltip="package: blitter.com/go/goutmp";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
fillcolor="lightyellow";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
label="[goutmp]";
|
||||
penwidth="0.8";
|
||||
|
||||
"blitter.com/go/goutmp.GetHost" [ fillcolor="moccasin" label="GetHost" penwidth="1.5" ]
|
||||
"blitter.com/go/goutmp.Put_utmp" [ fillcolor="moccasin" label="Put_utmp" penwidth="1.5" ]
|
||||
"blitter.com/go/goutmp.Unput_utmp" [ label="Unput_utmp" penwidth="1.5" fillcolor="moccasin" ]
|
||||
"blitter.com/go/goutmp.Put_lastlog_entry" [ fillcolor="moccasin" label="Put_lastlog_entry" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs" {
|
||||
fontsize="16";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
penwidth="0.8";
|
||||
fillcolor="lightyellow";
|
||||
label="[xs]";
|
||||
URL="/?f=blitter.com/go/xs";
|
||||
tooltip="package: blitter.com/go/xs";
|
||||
style="filled";
|
||||
|
||||
"blitter.com/go/xs.AuthUserByToken" [ fillcolor="moccasin" label="AuthUserByToken" penwidth="1.5" ]
|
||||
"blitter.com/go/xs.AuthUserByPasswd" [ label="AuthUserByPasswd" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
subgraph "cluster_*blitter.com/go/xs.Session" {
|
||||
tooltip="type: *blitter.com/go/xs.Session";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(*Session)";
|
||||
|
||||
"(*blitter.com/go/xs.Session).SetOp" [ fillcolor="moccasin" label="SetOp" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs.Session).SetWho" [ penwidth="1.5" fillcolor="moccasin" label="SetWho" ]
|
||||
"(*blitter.com/go/xs.Session).SetConnHost" [ penwidth="1.5" fillcolor="moccasin" label="SetConnHost" ]
|
||||
"(*blitter.com/go/xs.Session).SetTermType" [ fillcolor="moccasin" label="SetTermType" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs.Session).SetCmd" [ fillcolor="moccasin" label="SetCmd" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs.Session).SetAuthCookie" [ fillcolor="moccasin" label="SetAuthCookie" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs.Session).ClearAuthCookie" [ fillcolor="moccasin" label="ClearAuthCookie" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs.Session" {
|
||||
fillcolor="wheat2";
|
||||
label="(Session)";
|
||||
tooltip="type: blitter.com/go/xs.Session";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
|
||||
"(blitter.com/go/xs.Session).Op" [ fillcolor="moccasin" label="Op" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs.Session).Who" [ fillcolor="moccasin" label="Who" penwidth="1.5" ]
|
||||
"(blitter.com/go/xs.Session).ConnHost" [ penwidth="1.5" fillcolor="moccasin" label="ConnHost" ]
|
||||
"(blitter.com/go/xs.Session).Cmd" [ penwidth="1.5" fillcolor="moccasin" label="Cmd" ]
|
||||
"(blitter.com/go/xs.Session).AuthCookie" [ label="AuthCookie" penwidth="1.5" fillcolor="moccasin" ]
|
||||
"(blitter.com/go/xs.Session).TermType" [ fillcolor="moccasin" label="TermType" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/logger" {
|
||||
penwidth="0.8";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
fontname="bold";
|
||||
URL="/?f=blitter.com/go/xs/logger";
|
||||
fillcolor="lightyellow";
|
||||
rank="sink";
|
||||
label="[logger]";
|
||||
tooltip="package: blitter.com/go/xs/logger";
|
||||
|
||||
"blitter.com/go/xs/logger.LogNotice" [ fillcolor="moccasin" label="LogNotice" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/logger.LogDebug" [ fillcolor="moccasin" label="LogDebug" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/logger.LogErr" [ fillcolor="moccasin" label="LogErr" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/logger.New" [ label="New" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/xsnet" {
|
||||
penwidth="0.8";
|
||||
label="[xsnet]";
|
||||
fillcolor="lightyellow";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
URL="/?f=blitter.com/go/xs/xsnet";
|
||||
tooltip="package: blitter.com/go/xs/xsnet";
|
||||
fontsize="16";
|
||||
style="filled";
|
||||
|
||||
"blitter.com/go/xs/xsnet.Init" [ fillcolor="moccasin" label="Init" penwidth="1.5" ]
|
||||
"blitter.com/go/xs/xsnet.Listen" [ fillcolor="moccasin" label="Listen" penwidth="1.5" ]
|
||||
|
||||
subgraph "cluster_*blitter.com/go/xs/xsnet.Conn" {
|
||||
label="(*Conn)";
|
||||
tooltip="type: *blitter.com/go/xs/xsnet.Conn";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
|
||||
"(*blitter.com/go/xs/xsnet.Conn).Close" [ fillcolor="moccasin" label="Close" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).RemoteAddr" [ fillcolor="moccasin" label="RemoteAddr" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).EnableChaff" [ fillcolor="moccasin" label="EnableChaff" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).DisableChaff" [ label="DisableChaff" penwidth="1.5" fillcolor="moccasin" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).ShutdownChaff" [ fillcolor="moccasin" label="ShutdownChaff" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).SetStatus" [ fillcolor="moccasin" label="SetStatus" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).WritePacket" [ fillcolor="moccasin" label="WritePacket" penwidth="1.5" ]
|
||||
"(*blitter.com/go/xs/xsnet.Conn).SetupChaff" [ penwidth="1.5" fillcolor="moccasin" label="SetupChaff" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_*blitter.com/go/xs/xsnet.HKExListener" {
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(*HKExListener)";
|
||||
tooltip="type: *blitter.com/go/xs/xsnet.HKExListener";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
|
||||
"(*blitter.com/go/xs/xsnet.HKExListener).Accept" [ penwidth="1.5" fillcolor="moccasin" label="Accept" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/xsnet.Conn" {
|
||||
tooltip="type: blitter.com/go/xs/xsnet.Conn";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(Conn)";
|
||||
|
||||
"(blitter.com/go/xs/xsnet.Conn).Write" [ fillcolor="moccasin" label="Write" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_blitter.com/go/xs/xsnet.HKExListener" {
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(HKExListener)";
|
||||
tooltip="type: blitter.com/go/xs/xsnet.HKExListener";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
|
||||
"(blitter.com/go/xs/xsnet.HKExListener).Close" [ label="Close" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_context" {
|
||||
fontsize="16";
|
||||
fillcolor="#E0FFE1";
|
||||
label="[context]";
|
||||
tooltip="package: context";
|
||||
penwidth="0.8";
|
||||
style="filled";
|
||||
fontname="bold";
|
||||
rank="sink";
|
||||
URL="/?f=context";
|
||||
|
||||
|
||||
subgraph "cluster_context.deadlineExceededError" {
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="#c2e3c2";
|
||||
label="(deadlineExceededError)";
|
||||
tooltip="type: context.deadlineExceededError";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
fontcolor="#222222";
|
||||
|
||||
"(context.deadlineExceededError).Error" [ fillcolor="#adedad" label="Error" penwidth="1.5" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_github.com/kr/pty" {
|
||||
label="[pty]";
|
||||
URL="/?f=github.com/kr/pty";
|
||||
penwidth="0.8";
|
||||
style="filled";
|
||||
fillcolor="lightyellow";
|
||||
rank="sink";
|
||||
fontsize="16";
|
||||
fontname="bold";
|
||||
tooltip="package: github.com/kr/pty";
|
||||
|
||||
"github.com/kr/pty.Start" [ fillcolor="moccasin" label="Start" penwidth="1.5" ]
|
||||
"github.com/kr/pty.Setsize" [ label="Setsize" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
}
|
||||
|
||||
subgraph "cluster_github.com/pkg/errors" {
|
||||
fontname="bold";
|
||||
label="[errors]";
|
||||
style="filled";
|
||||
fontsize="16";
|
||||
fillcolor="lightyellow";
|
||||
rank="sink";
|
||||
URL="/?f=github.com/pkg/errors";
|
||||
tooltip="package: github.com/pkg/errors";
|
||||
penwidth="0.8";
|
||||
|
||||
|
||||
subgraph "cluster_*github.com/pkg/errors.fundamental" {
|
||||
fontcolor="#222222";
|
||||
labelloc="b";
|
||||
style="rounded,filled";
|
||||
fillcolor="wheat2";
|
||||
label="(*fundamental)";
|
||||
tooltip="type: *github.com/pkg/errors.fundamental";
|
||||
penwidth="0.5";
|
||||
fontsize="15";
|
||||
|
||||
"(*github.com/pkg/errors.fundamental).Error" [ label="Error" penwidth="1.5" fillcolor="moccasin" ]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs/xsnet.Conn).Close" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs.Session).SetOp" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs.Session).SetWho" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs.Session).SetConnHost" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs.Session).SetTermType" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs.Session).SetCmd" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs.Session).SetAuthCookie" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(blitter.com/go/xs.Session).Op" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(blitter.com/go/xs.Session).Who" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(blitter.com/go/xs.Session).ConnHost" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(blitter.com/go/xs.Session).Cmd" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(blitter.com/go/xs.Session).AuthCookie" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs.AuthUserByToken" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs.Session).ClearAuthCookie" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs.AuthUserByPasswd" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(blitter.com/go/xs/xsnet.Conn).Write" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs/logger.LogNotice" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs/xsnet.Conn).RemoteAddr" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/goutmp.GetHost" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs/xsd.GenAuthToken" [ ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(blitter.com/go/xs.Session).TermType" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "github.com/kr/pty.Start" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/xsd.runShellAs$1" [ arrowhead="normalnoneodiamond" ]
|
||||
"blitter.com/go/xs/xsd.ptsName" -> "blitter.com/go/xs/xsd.ioctl" [ ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/xsd.ptsName" [ ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/goutmp.Put_utmp" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$2" -> "blitter.com/go/goutmp.Unput_utmp" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/xsd.runShellAs$2" [ arrowhead="normalnoneodiamond" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/goutmp.Put_lastlog_entry" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$3" -> "github.com/kr/pty.Setsize" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/xsd.runShellAs$3" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$4" -> "(context.deadlineExceededError).Error" [ color="saddlebrown" style="dashed" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$4" -> "(*github.com/pkg/errors.fundamental).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/xsd.runShellAs$4" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "(*blitter.com/go/xs/xsnet.Conn).EnableChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$5" -> "(*blitter.com/go/xs/xsnet.Conn).DisableChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$5" -> "(*blitter.com/go/xs/xsnet.Conn).ShutdownChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/xsd.runShellAs$5" [ arrowhead="normalnoneodiamond" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$6" -> "(context.deadlineExceededError).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs$6" -> "(*github.com/pkg/errors.fundamental).Error" [ style="dashed" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/xsd.runShellAs$6" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "blitter.com/go/xs/logger.LogDebug" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runShellAs" -> "(*blitter.com/go/xs/xsnet.Conn).SetStatus" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs/xsd.runShellAs" [ ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs/logger.LogErr" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs/xsnet.Conn).SetStatus" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runClientToServerCopyAs" -> "(*blitter.com/go/xs/xsnet.Conn).EnableChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runClientToServerCopyAs" -> "(*blitter.com/go/xs/xsnet.Conn).DisableChaff" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runClientToServerCopyAs" -> "(*blitter.com/go/xs/xsnet.Conn).ShutdownChaff" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs/xsd.runClientToServerCopyAs" [ ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "(*blitter.com/go/xs/xsnet.Conn).WritePacket" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runServerToClientCopyAs" -> "(*blitter.com/go/xs/xsnet.Conn).EnableChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runServerToClientCopyAs" -> "(*blitter.com/go/xs/xsnet.Conn).DisableChaff" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.runServerToClientCopyAs" -> "(*blitter.com/go/xs/xsnet.Conn).ShutdownChaff" [ color="saddlebrown" arrowhead="normalnoneodiamond" ]
|
||||
"blitter.com/go/xs/xsd.main$2" -> "blitter.com/go/xs/xsd.runServerToClientCopyAs" [ ]
|
||||
"blitter.com/go/xs/xsd.main" -> "blitter.com/go/xs/logger.New" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main" -> "blitter.com/go/xs/xsnet.Init" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main$1" -> "blitter.com/go/xs/logger.LogNotice" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main" -> "blitter.com/go/xs/xsd.main$1" [ arrowhead="normalnoneodot" ]
|
||||
"blitter.com/go/xs/xsd.main" -> "blitter.com/go/xs/xsnet.Listen" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main" -> "(blitter.com/go/xs/xsnet.HKExListener).Close" [ arrowhead="normalnoneodiamond" color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main" -> "(*blitter.com/go/xs/xsnet.HKExListener).Accept" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main" -> "(*blitter.com/go/xs/xsnet.Conn).SetupChaff" [ color="saddlebrown" ]
|
||||
"blitter.com/go/xs/xsd.main" -> "blitter.com/go/xs/xsd.main$2" [ arrowhead="normalnoneodot" ]
|
||||
}
|
||||
849
xsd/xsd.go
Executable file
849
xsd/xsd.go
Executable file
|
|
@ -0,0 +1,849 @@
|
|||
// xsd server
|
||||
//
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"os/user"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"blitter.com/go/goutmp"
|
||||
xs "blitter.com/go/xs"
|
||||
"blitter.com/go/xs/logger"
|
||||
"blitter.com/go/xs/xsnet"
|
||||
"github.com/creack/pty"
|
||||
)
|
||||
|
||||
var (
|
||||
version string
|
||||
gitCommit string // set in -ldflags by build
|
||||
|
||||
useSysLogin bool
|
||||
kcpMode string // set to a valid KCP BlockCrypt alg tag to use rather than TCP
|
||||
|
||||
// Log - syslog output (with no -d)
|
||||
Log *logger.Writer
|
||||
)
|
||||
|
||||
func ioctl(fd, request, argp uintptr) error {
|
||||
if _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, fd, request, argp, 0, 0, 0); e != 0 {
|
||||
return e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ptsName(fd uintptr) (string, error) {
|
||||
var n uintptr
|
||||
err := ioctl(fd, syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n)))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("/dev/pts/%d", n), nil
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- */
|
||||
// Perform a client->server copy
|
||||
func runClientToServerCopyAs(who, ttype string, conn *xsnet.Conn, fpath string, chaffing bool) (exitStatus uint32, err error) {
|
||||
u, _ := user.Lookup(who) // nolint: gosec
|
||||
var uid, gid uint32
|
||||
fmt.Sscanf(u.Uid, "%d", &uid) // nolint: gosec,errcheck
|
||||
fmt.Sscanf(u.Gid, "%d", &gid) // nolint: gosec,errcheck
|
||||
log.Println("uid:", uid, "gid:", gid)
|
||||
|
||||
// Need to clear server's env and set key vars of the
|
||||
// target user. This isn't perfect (TERM doesn't seem to
|
||||
// work 100%; ANSI/xterm colour isn't working even
|
||||
// if we set "xterm" or "ansi" here; and line count
|
||||
// reported by 'stty -a' defaults to 24 regardless
|
||||
// of client shell window used to run client.
|
||||
// Investigate -- rlm 2018-01-26)
|
||||
os.Clearenv()
|
||||
os.Setenv("HOME", u.HomeDir) // nolint: gosec,errcheck
|
||||
os.Setenv("TERM", ttype) // nolint: gosec,errcheck
|
||||
os.Setenv("XS_SESSION", "1") // nolint: gosec,errcheck
|
||||
|
||||
var c *exec.Cmd
|
||||
cmdName := xs.GetTool("tar")
|
||||
|
||||
var destDir string
|
||||
if path.IsAbs(fpath) {
|
||||
destDir = fpath
|
||||
} else {
|
||||
destDir = path.Join(u.HomeDir, fpath)
|
||||
}
|
||||
|
||||
cmdArgs := []string{"-xz", "-C", destDir}
|
||||
|
||||
// NOTE the lack of quotes around --xform option's sed expression.
|
||||
// When args are passed in exec() format, no quoting is required
|
||||
// (as this isn't input from a shell) (right? -rlm 20180823)
|
||||
//cmdArgs := []string{"-x", "-C", destDir, `--xform=s#.*/\(.*\)#\1#`}
|
||||
fmt.Println(cmdName, cmdArgs)
|
||||
c = exec.Command(cmdName, cmdArgs...) // nolint: gosec
|
||||
|
||||
c.Dir = destDir
|
||||
|
||||
//If os.Clearenv() isn't called by server above these will be seen in the
|
||||
//client's session env.
|
||||
//c.Env = []string{"HOME=" + u.HomeDir, "SUDO_GID=", "SUDO_UID=", "SUDO_USER=", "SUDO_COMMAND=", "MAIL=", "LOGNAME="+who}
|
||||
//c.Dir = u.HomeDir
|
||||
c.SysProcAttr = &syscall.SysProcAttr{}
|
||||
c.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}
|
||||
c.Stdin = conn
|
||||
c.Stdout = os.Stdout
|
||||
c.Stderr = os.Stderr
|
||||
|
||||
if chaffing {
|
||||
conn.EnableChaff()
|
||||
}
|
||||
defer conn.DisableChaff()
|
||||
defer conn.ShutdownChaff()
|
||||
|
||||
// Start the command (no pty)
|
||||
log.Printf("[%v %v]\n", cmdName, cmdArgs)
|
||||
err = c.Start() // returns immediately
|
||||
/////////////
|
||||
// NOTE: There is, apparently, a bug in Go stdlib here. Start()
|
||||
// can actually return immediately, on a command which *does*
|
||||
// start but exits quickly, with c.Wait() error
|
||||
// "c.Wait status: exec: not started".
|
||||
// As in this example, attempting a client->server copy to
|
||||
// a nonexistent remote dir (it's tar exiting right away, exitStatus
|
||||
// 2, stderr
|
||||
// /bin/tar -xz -C /home/someuser/nosuchdir
|
||||
// stderr: fork/exec /bin/tar: no such file or directory
|
||||
//
|
||||
// In this case, c.Wait() won't give us the real
|
||||
// exit status (is it lost?).
|
||||
/////////////
|
||||
if err != nil {
|
||||
log.Println("cmd exited immediately. Cannot get cmd.Wait().ExitStatus()")
|
||||
err = errors.New("cmd exited prematurely")
|
||||
//exitStatus = uint32(254)
|
||||
exitStatus = xsnet.CSEExecFail
|
||||
} else {
|
||||
if err := c.Wait(); err != nil {
|
||||
//fmt.Println("*** c.Wait() done ***")
|
||||
if exiterr, ok := err.(*exec.ExitError); ok {
|
||||
// The program has exited with an exit code != 0
|
||||
|
||||
// This works on both Unix and Windows. Although package
|
||||
// syscall is generally platform dependent, WaitStatus is
|
||||
// defined for both Unix and Windows and in both cases has
|
||||
// an ExitStatus() method with the same signature.
|
||||
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
|
||||
exitStatus = uint32(status.ExitStatus())
|
||||
//err = errors.New("cmd returned nonzero status")
|
||||
log.Printf("Exit Status: %d\n", exitStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
log.Println("*** client->server cp finished ***")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Perform a server->client copy
|
||||
func runServerToClientCopyAs(who, ttype string, conn *xsnet.Conn, srcPath string, chaffing bool) (exitStatus uint32, err error) {
|
||||
u, err := user.Lookup(who)
|
||||
if err != nil {
|
||||
exitStatus = 1
|
||||
return
|
||||
}
|
||||
var uid, gid uint32
|
||||
_, _ = fmt.Sscanf(u.Uid, "%d", &uid) // nolint: gosec
|
||||
_, _ = fmt.Sscanf(u.Gid, "%d", &gid) // nolint: gosec
|
||||
log.Println("uid:", uid, "gid:", gid)
|
||||
|
||||
// Need to clear server's env and set key vars of the
|
||||
// target user. This isn't perfect (TERM doesn't seem to
|
||||
// work 100%; ANSI/xterm colour isn't working even
|
||||
// if we set "xterm" or "ansi" here; and line count
|
||||
// reported by 'stty -a' defaults to 24 regardless
|
||||
// of client shell window used to run client.
|
||||
// Investigate -- rlm 2018-01-26)
|
||||
os.Clearenv()
|
||||
_ = os.Setenv("HOME", u.HomeDir) // nolint: gosec
|
||||
_ = os.Setenv("TERM", ttype) // nolint: gosec
|
||||
_ = os.Setenv("XS_SESSION", "1") // nolint: gosec
|
||||
|
||||
var c *exec.Cmd
|
||||
cmdName := xs.GetTool("tar")
|
||||
if !path.IsAbs(srcPath) {
|
||||
srcPath = fmt.Sprintf("%s%c%s", u.HomeDir, os.PathSeparator, srcPath)
|
||||
}
|
||||
|
||||
srcDir, srcBase := path.Split(srcPath)
|
||||
cmdArgs := []string{"-cz", "-C", srcDir, "-f", "-", srcBase}
|
||||
|
||||
c = exec.Command(cmdName, cmdArgs...) // nolint: gosec
|
||||
|
||||
//If os.Clearenv() isn't called by server above these will be seen in the
|
||||
//client's session env.
|
||||
//c.Env = []string{"HOME=" + u.HomeDir, "SUDO_GID=", "SUDO_UID=", "SUDO_USER=", "SUDO_COMMAND=", "MAIL=", "LOGNAME="+who}
|
||||
c.Dir = u.HomeDir
|
||||
c.SysProcAttr = &syscall.SysProcAttr{}
|
||||
c.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}
|
||||
c.Stdout = conn
|
||||
// Stderr sinkholing (or buffering to something other than stdout)
|
||||
// is important. Any extraneous output to tarpipe messes up remote
|
||||
// side as it's expecting pure tar data.
|
||||
// (For example, if user specifies abs paths, tar outputs
|
||||
// "Removing leading '/' from path names")
|
||||
stdErrBuffer := new(bytes.Buffer)
|
||||
c.Stderr = stdErrBuffer
|
||||
//c.Stderr = nil
|
||||
|
||||
if chaffing {
|
||||
conn.EnableChaff()
|
||||
}
|
||||
//defer conn.Close()
|
||||
defer conn.DisableChaff()
|
||||
defer conn.ShutdownChaff()
|
||||
|
||||
// Start the command (no pty)
|
||||
log.Printf("[%v %v]\n", cmdName, cmdArgs)
|
||||
err = c.Start() // returns immediately
|
||||
if err != nil {
|
||||
log.Printf("Command finished with error: %v", err)
|
||||
return xsnet.CSEExecFail, err // !?
|
||||
}
|
||||
if err := c.Wait(); err != nil {
|
||||
//fmt.Println("*** c.Wait() done ***")
|
||||
if exiterr, ok := err.(*exec.ExitError); ok {
|
||||
// The program has exited with an exit code != 0
|
||||
|
||||
// This works on both Unix and Windows. Although package
|
||||
// syscall is generally platform dependent, WaitStatus is
|
||||
// defined for both Unix and Windows and in both cases has
|
||||
// an ExitStatus() method with the same signature.
|
||||
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
|
||||
exitStatus = uint32(status.ExitStatus())
|
||||
if len(stdErrBuffer.Bytes()) > 0 {
|
||||
log.Print(stdErrBuffer)
|
||||
}
|
||||
log.Printf("Exit Status: %d", exitStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
//fmt.Println("*** server->client cp finished ***")
|
||||
return
|
||||
}
|
||||
|
||||
// Run a command (via default shell) as a specific user
|
||||
//
|
||||
// Uses ptys to support commands which expect a terminal.
|
||||
// nolint: gocyclo
|
||||
func runShellAs(who, hname, ttype, cmd string, interactive bool, conn *xsnet.Conn, chaffing bool) (exitStatus uint32, err error) {
|
||||
var wg sync.WaitGroup
|
||||
u, err := user.Lookup(who)
|
||||
if err != nil {
|
||||
exitStatus = 1
|
||||
return
|
||||
}
|
||||
var uid, gid uint32
|
||||
_, _ = fmt.Sscanf(u.Uid, "%d", &uid) // nolint: gosec
|
||||
_, _ = fmt.Sscanf(u.Gid, "%d", &gid) // nolint: gosec
|
||||
log.Println("uid:", uid, "gid:", gid)
|
||||
|
||||
// Need to clear server's env and set key vars of the
|
||||
// target user. This isn't perfect (TERM doesn't seem to
|
||||
// work 100%; ANSI/xterm colour isn't working even
|
||||
// if we set "xterm" or "ansi" here; and line count
|
||||
// reported by 'stty -a' defaults to 24 regardless
|
||||
// of client shell window used to run client.
|
||||
// Investigate -- rlm 2018-01-26)
|
||||
os.Clearenv()
|
||||
_ = os.Setenv("HOME", u.HomeDir) // nolint: gosec
|
||||
_ = os.Setenv("TERM", ttype) // nolint: gosec
|
||||
_ = os.Setenv("XS_SESSION", "1") // nolint: gosec
|
||||
|
||||
var c *exec.Cmd
|
||||
if interactive {
|
||||
if useSysLogin {
|
||||
// Use the server's login binary (post-auth
|
||||
// which is still done via our own bcrypt file)
|
||||
// Things UNIX login does, like print the 'motd',
|
||||
// and use the shell specified by /etc/passwd, will be done
|
||||
// automagically, at the cost of another external tool
|
||||
// dependency.
|
||||
//
|
||||
c = exec.Command(xs.GetTool("login"), "-f", "-p", who) // nolint: gosec
|
||||
} else {
|
||||
c = exec.Command(xs.GetTool("bash"), "-i", "-l") // nolint: gosec
|
||||
}
|
||||
} else {
|
||||
c = exec.Command(xs.GetTool("bash"), "-c", cmd) // nolint: gosec
|
||||
}
|
||||
//If os.Clearenv() isn't called by server above these will be seen in the
|
||||
//client's session env.
|
||||
//c.Env = []string{"HOME=" + u.HomeDir, "SUDO_GID=", "SUDO_UID=", "SUDO_USER=", "SUDO_COMMAND=", "MAIL=", "LOGNAME="+who}
|
||||
c.Dir = u.HomeDir
|
||||
c.SysProcAttr = &syscall.SysProcAttr{}
|
||||
if useSysLogin {
|
||||
// If using server's login binary, drop to user creds
|
||||
// is taken care of by it.
|
||||
c.SysProcAttr.Credential = &syscall.Credential{}
|
||||
} else {
|
||||
c.SysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: gid}
|
||||
}
|
||||
|
||||
// Start the command with a pty.
|
||||
ptmx, err := pty.Start(c) // returns immediately with ptmx file
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return xsnet.CSEPtyExecFail, err
|
||||
}
|
||||
// Make sure to close the pty at the end.
|
||||
// #gv:s/label=\"runShellAs\$1\"/label=\"deferPtmxClose\"/
|
||||
defer func() {
|
||||
//logger.LogDebug(fmt.Sprintf("[Exited process was %d]", c.Process.Pid))
|
||||
_ = ptmx.Close()
|
||||
}() // nolint: gosec
|
||||
|
||||
// get pty info for system accounting (who, lastlog)
|
||||
pts, pe := ptsName(ptmx.Fd())
|
||||
if pe != nil {
|
||||
return xsnet.CSEPtyGetNameFail, err
|
||||
}
|
||||
utmpx := goutmp.Put_utmp(who, pts, hname)
|
||||
defer func() { goutmp.Unput_utmp(utmpx) }()
|
||||
goutmp.Put_lastlog_entry("xs", who, pts, hname)
|
||||
|
||||
log.Printf("[%s]\n", cmd)
|
||||
if err != nil {
|
||||
log.Printf("Command finished with error: %v", err)
|
||||
} else {
|
||||
// Watch for term resizes
|
||||
// #gv:s/label=\"runShellAs\$2\"/label=\"termResizeWatcher\"/
|
||||
go func() {
|
||||
for sz := range conn.WinCh {
|
||||
log.Printf("[Setting term size to: %v %v]\n", sz.Rows, sz.Cols)
|
||||
pty.Setsize(ptmx, &pty.Winsize{Rows: sz.Rows, Cols: sz.Cols}) // nolint: gosec,errcheck
|
||||
}
|
||||
log.Println("*** WinCh goroutine done ***")
|
||||
}()
|
||||
|
||||
// Copy stdin to the pty.. (bgnd goroutine)
|
||||
// #gv:s/label=\"runShellAs\$3\"/label=\"stdinToPtyWorker\"/
|
||||
go func() {
|
||||
_, e := io.Copy(ptmx, conn)
|
||||
if e != nil {
|
||||
log.Println("** stdin->pty ended **:", e.Error())
|
||||
} else {
|
||||
log.Println("*** stdin->pty goroutine done ***")
|
||||
}
|
||||
}()
|
||||
|
||||
if chaffing {
|
||||
conn.EnableChaff()
|
||||
}
|
||||
// #gv:s/label=\"runShellAs\$4\"/label=\"deferChaffShutdown\"/
|
||||
defer func() {
|
||||
conn.DisableChaff()
|
||||
conn.ShutdownChaff()
|
||||
}()
|
||||
|
||||
// ..and the pty to stdout.
|
||||
// This may take some time exceeding that of the
|
||||
// actual command's lifetime, so the c.Wait() below
|
||||
// must synchronize with the completion of this goroutine
|
||||
// to ensure all stdout data gets to the client before
|
||||
// connection is closed.
|
||||
wg.Add(1)
|
||||
// #gv:s/label=\"runShellAs\$5\"/label=\"ptyToStdoutWorker\"/
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, e := io.Copy(conn, ptmx)
|
||||
if e != nil {
|
||||
log.Println("** pty->stdout ended **:", e.Error())
|
||||
} else {
|
||||
// The above io.Copy() will exit when the command attached
|
||||
// to the pty exits
|
||||
log.Println("*** pty->stdout goroutine done ***")
|
||||
}
|
||||
}()
|
||||
|
||||
if err := c.Wait(); err != nil {
|
||||
//fmt.Println("*** c.Wait() done ***")
|
||||
if exiterr, ok := err.(*exec.ExitError); ok {
|
||||
// The program has exited with an exit code != 0
|
||||
|
||||
// This works on both Unix and Windows. Although package
|
||||
// syscall is generally platform dependent, WaitStatus is
|
||||
// defined for both Unix and Windows and in both cases has
|
||||
// an ExitStatus() method with the same signature.
|
||||
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
|
||||
exitStatus = uint32(status.ExitStatus())
|
||||
log.Printf("Exit Status: %d", exitStatus)
|
||||
}
|
||||
}
|
||||
conn.SetStatus(xsnet.CSOType(exitStatus))
|
||||
} else {
|
||||
logger.LogDebug("*** Main proc has exited. ***")
|
||||
// Background jobs still may be running; close the
|
||||
// pty anyway, so the client can return before
|
||||
// wg.Wait() below completes (Issue #18)
|
||||
if interactive {
|
||||
_ = ptmx.Close()
|
||||
}
|
||||
}
|
||||
wg.Wait() // Wait on pty->stdout completion to client
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GenAuthToken generates a pseudorandom auth token for a specific
|
||||
// user from a specific host to allow non-interactive logins.
|
||||
func GenAuthToken(who string, connhost string) string {
|
||||
//tokenA, e := os.Hostname()
|
||||
//if e != nil {
|
||||
// tokenA = "badhost"
|
||||
//}
|
||||
tokenA := connhost
|
||||
|
||||
tokenB := make([]byte, 64)
|
||||
_, _ = rand.Read(tokenB) // nolint: gosec
|
||||
return fmt.Sprintf("%s:%s", tokenA, hex.EncodeToString(tokenB))
|
||||
}
|
||||
|
||||
var (
|
||||
aKEXAlgs allowedKEXAlgs
|
||||
aCipherAlgs allowedCipherAlgs
|
||||
aHMACAlgs allowedHMACAlgs
|
||||
)
|
||||
|
||||
type allowedKEXAlgs []string // TODO
|
||||
type allowedCipherAlgs []string // TODO
|
||||
type allowedHMACAlgs []string // TODO
|
||||
|
||||
func (a allowedKEXAlgs) allowed(k xsnet.KEXAlg) bool {
|
||||
for i := 0; i < len(a); i++ {
|
||||
if a[i] == "KEX_all" || a[i] == k.String() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *allowedKEXAlgs) String() string {
|
||||
return fmt.Sprintf("allowedKEXAlgs: %v", *a)
|
||||
}
|
||||
|
||||
func (a *allowedKEXAlgs) Set(value string) error {
|
||||
*a = append(*a, strings.TrimSpace(value))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a allowedCipherAlgs) allowed(c xsnet.CSCipherAlg) bool {
|
||||
for i := 0; i < len(a); i++ {
|
||||
if a[i] == "C_all" || a[i] == c.String() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *allowedCipherAlgs) String() string {
|
||||
return fmt.Sprintf("allowedCipherAlgs: %v", *a)
|
||||
}
|
||||
|
||||
func (a *allowedCipherAlgs) Set(value string) error {
|
||||
*a = append(*a, strings.TrimSpace(value))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a allowedHMACAlgs) allowed(h xsnet.CSHmacAlg) bool {
|
||||
for i := 0; i < len(a); i++ {
|
||||
if a[i] == "H_all" || a[i] == h.String() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *allowedHMACAlgs) String() string {
|
||||
return fmt.Sprintf("allowedHMACAlgs: %v", *a)
|
||||
}
|
||||
|
||||
func (a *allowedHMACAlgs) Set(value string) error {
|
||||
*a = append(*a, strings.TrimSpace(value))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Main server that listens and spawns goroutines for each
|
||||
// connecting client to serve interactive or file copy sessions
|
||||
// and any requested tunnels.
|
||||
// Note that this server does not do UNIX forks of itself to give
|
||||
// each client its own separate manager process, so if the main
|
||||
// daemon dies, all clients will be rudely disconnected.
|
||||
// Consider this when planning to restart or upgrade in-place an installation.
|
||||
// TODO: reduce gocyclo
|
||||
func main() {
|
||||
var vopt bool
|
||||
var chaffEnabled bool
|
||||
var chaffFreqMin uint
|
||||
var chaffFreqMax uint
|
||||
var chaffBytesMax uint
|
||||
var dbg bool
|
||||
var laddr string
|
||||
|
||||
var useSystemPasswd bool
|
||||
|
||||
flag.BoolVar(&vopt, "v", false, "show version")
|
||||
flag.StringVar(&laddr, "l", ":2000", "interface[:port] to listen")
|
||||
flag.StringVar(&kcpMode, "K", "unused", `set to one of ["KCP_NONE","KCP_AES", "KCP_BLOWFISH", "KCP_CAST5", "KCP_SM4", "KCP_SALSA20", "KCP_SIMPLEXOR", "KCP_TEA", "KCP_3DES", "KCP_TWOFISH", "KCP_XTEA"] to use KCP (github.com/xtaci/kcp-go) reliable UDP instead of TCP`)
|
||||
flag.BoolVar(&useSysLogin, "L", false, "use system login")
|
||||
flag.BoolVar(&chaffEnabled, "e", true, "enable chaff pkts")
|
||||
flag.UintVar(&chaffFreqMin, "f", 100, "chaff pkt freq min (msecs)")
|
||||
flag.UintVar(&chaffFreqMax, "F", 5000, "chaff pkt freq max (msecs)")
|
||||
flag.UintVar(&chaffBytesMax, "B", 64, "chaff pkt size max (bytes)")
|
||||
flag.BoolVar(&useSystemPasswd, "s", true, "use system shadow passwds")
|
||||
flag.BoolVar(&dbg, "d", false, "debug logging")
|
||||
|
||||
flag.Var(&aKEXAlgs, "aK", `List of allowed KEX algs (eg. 'KEXAlgA KEXAlgB ... KEXAlgN') (default allow all)`)
|
||||
flag.Var(&aCipherAlgs, "aC", `List of allowed ciphers (eg. 'CipherAlgA CipherAlgB ... CipherAlgN') (default allow all)`)
|
||||
flag.Var(&aHMACAlgs, "aH", `List of allowed HMACs (eg. 'HMACAlgA HMACAlgB ... HMACAlgN') (default allow all)`)
|
||||
|
||||
flag.Parse()
|
||||
|
||||
if vopt {
|
||||
fmt.Printf("version %s (%s)\n", version, gitCommit)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
{
|
||||
me, e := user.Current()
|
||||
if e != nil || me.Uid != "0" {
|
||||
log.Fatal("Must run as root.")
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce some sane min/max vals on chaff flags
|
||||
if chaffFreqMin < 2 {
|
||||
chaffFreqMin = 2
|
||||
}
|
||||
if chaffFreqMax == 0 {
|
||||
chaffFreqMax = chaffFreqMin + 1
|
||||
}
|
||||
if chaffBytesMax == 0 || chaffBytesMax > 4096 {
|
||||
chaffBytesMax = 64
|
||||
}
|
||||
|
||||
Log, _ = logger.New(logger.LOG_DAEMON|logger.LOG_DEBUG|logger.LOG_NOTICE|logger.LOG_ERR, "xsd") // nolint: gosec
|
||||
xsnet.Init(dbg, "xsd", logger.LOG_DAEMON|logger.LOG_DEBUG|logger.LOG_NOTICE|logger.LOG_ERR)
|
||||
if dbg {
|
||||
log.SetOutput(Log)
|
||||
} else {
|
||||
log.SetOutput(ioutil.Discard)
|
||||
}
|
||||
|
||||
// Set up allowed algs, if specified (default allow all)
|
||||
if len(aKEXAlgs) == 0 {
|
||||
aKEXAlgs = []string{"KEX_all"}
|
||||
}
|
||||
logger.LogNotice(fmt.Sprintf("Allowed KEXAlgs: %v\n", aKEXAlgs)) // nolint: gosec,errcheck
|
||||
|
||||
if len(aCipherAlgs) == 0 {
|
||||
aCipherAlgs = []string{"C_all"}
|
||||
}
|
||||
logger.LogNotice(fmt.Sprintf("Allowed CipherAlgs: %v\n", aCipherAlgs)) // nolint: gosec,errcheck
|
||||
|
||||
if len(aHMACAlgs) == 0 {
|
||||
aHMACAlgs = []string{"H_all"}
|
||||
}
|
||||
logger.LogNotice(fmt.Sprintf("Allowed HMACAlgs: %v\n", aHMACAlgs)) // nolint: gosec,errcheck
|
||||
|
||||
// Set up handler for daemon signalling
|
||||
exitCh := make(chan os.Signal, 1)
|
||||
signal.Notify(exitCh, os.Signal(syscall.SIGTERM), os.Signal(syscall.SIGINT), os.Signal(syscall.SIGHUP), os.Signal(syscall.SIGUSR1), os.Signal(syscall.SIGUSR2))
|
||||
go func() {
|
||||
for {
|
||||
sig := <-exitCh
|
||||
switch sig.String() {
|
||||
case "terminated":
|
||||
logger.LogNotice(fmt.Sprintf("[Got signal: %s]", sig)) // nolint: gosec,errcheck
|
||||
signal.Reset()
|
||||
syscall.Kill(0, syscall.SIGTERM) // nolint: gosec,errcheck
|
||||
case "interrupt":
|
||||
logger.LogNotice(fmt.Sprintf("[Got signal: %s]", sig)) // nolint: gosec,errcheck
|
||||
signal.Reset()
|
||||
syscall.Kill(0, syscall.SIGINT) // nolint: gosec,errcheck
|
||||
case "hangup":
|
||||
logger.LogNotice(fmt.Sprintf("[Got signal: %s - nop]", sig)) // nolint:gosec,errcheck
|
||||
default:
|
||||
logger.LogNotice(fmt.Sprintf("[Got signal: %s - ignored]", sig)) // nolint: gosec,errcheck
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
proto := "tcp"
|
||||
if kcpMode != "unused" {
|
||||
proto = "kcp"
|
||||
}
|
||||
l, err := xsnet.Listen(proto, laddr, kcpMode)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer l.Close() // nolint: errcheck
|
||||
|
||||
log.Println("Serving on", laddr)
|
||||
for {
|
||||
// Wait for a connection.
|
||||
// Then check if client-proposed algs are allowed
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
log.Printf("Accept() got error(%v), hanging up.\n", err)
|
||||
} else if !aKEXAlgs.allowed(conn.KEX()) {
|
||||
log.Printf("Accept() rejected for banned KEX alg %d, hanging up.\n", conn.KEX())
|
||||
conn.SetStatus(xsnet.CSEKEXAlgDenied)
|
||||
conn.Close()
|
||||
} else if !aCipherAlgs.allowed(conn.CAlg()) {
|
||||
log.Printf("Accept() rejected for banned Cipher alg %d, hanging up.\n", conn.CAlg())
|
||||
conn.SetStatus(xsnet.CSECipherAlgDenied)
|
||||
conn.Close()
|
||||
} else if !aHMACAlgs.allowed(conn.HAlg()) {
|
||||
log.Printf("Accept() rejected for banned HMAC alg %d, hanging up.\n", conn.HAlg())
|
||||
conn.SetStatus(xsnet.CSEHMACAlgDenied)
|
||||
conn.Close()
|
||||
} else {
|
||||
log.Println("Accepted client")
|
||||
|
||||
// Set up chaffing to client
|
||||
// Will only start when runShellAs() is called
|
||||
// after stdin/stdout are hooked up
|
||||
conn.SetupChaff(chaffFreqMin, chaffFreqMax, chaffBytesMax) // configure server->client chaffing
|
||||
|
||||
// Handle the connection in a new goroutine.
|
||||
// The loop then returns to accepting, so that
|
||||
// multiple connections may be served concurrently.
|
||||
go func(hc *xsnet.Conn) (e error) {
|
||||
defer hc.Close() // nolint: errcheck
|
||||
|
||||
// Start login timeout here and disconnect if user/pass phase stalls
|
||||
loginTimeout := time.AfterFunc(30*time.Second, func() {
|
||||
logger.LogNotice(fmt.Sprintln("Login timed out")) // nolint: errcheck,gosec
|
||||
hc.Write([]byte{0}) // nolint: gosec,errcheck
|
||||
hc.Close()
|
||||
})
|
||||
|
||||
//We use io.ReadFull() here to guarantee we consume
|
||||
//just the data we want for the xs.Session, and no more.
|
||||
//Otherwise data will be sitting in the channel that isn't
|
||||
//passed down to the command handlers.
|
||||
var rec xs.Session
|
||||
var len1, len2, len3, len4, len5, len6 uint32
|
||||
|
||||
n, err := fmt.Fscanf(hc, "%d %d %d %d %d %d\n", &len1, &len2, &len3, &len4, &len5, &len6)
|
||||
log.Printf("xs.Session read:%d %d %d %d %d %d\n", len1, len2, len3, len4, len5, len6)
|
||||
|
||||
if err != nil || n < 6 {
|
||||
log.Println("[Bad xs.Session fmt]")
|
||||
return err
|
||||
}
|
||||
|
||||
tmp := make([]byte, len1)
|
||||
_, err = io.ReadFull(hc, tmp)
|
||||
if err != nil {
|
||||
log.Println("[Bad xs.Session.Op]")
|
||||
return err
|
||||
}
|
||||
rec.SetOp(tmp)
|
||||
|
||||
tmp = make([]byte, len2)
|
||||
_, err = io.ReadFull(hc, tmp)
|
||||
if err != nil {
|
||||
log.Println("[Bad xs.Session.Who]")
|
||||
return err
|
||||
}
|
||||
rec.SetWho(tmp)
|
||||
|
||||
tmp = make([]byte, len3)
|
||||
_, err = io.ReadFull(hc, tmp)
|
||||
if err != nil {
|
||||
log.Println("[Bad xs.Session.ConnHost]")
|
||||
return err
|
||||
}
|
||||
rec.SetConnHost(tmp)
|
||||
|
||||
tmp = make([]byte, len4)
|
||||
_, err = io.ReadFull(hc, tmp)
|
||||
if err != nil {
|
||||
log.Println("[Bad xs.Session.TermType]")
|
||||
return err
|
||||
}
|
||||
rec.SetTermType(tmp)
|
||||
|
||||
tmp = make([]byte, len5)
|
||||
_, err = io.ReadFull(hc, tmp)
|
||||
if err != nil {
|
||||
log.Println("[Bad xs.Session.Cmd]")
|
||||
return err
|
||||
}
|
||||
rec.SetCmd(tmp)
|
||||
|
||||
tmp = make([]byte, len6)
|
||||
_, err = io.ReadFull(hc, tmp)
|
||||
if err != nil {
|
||||
log.Println("[Bad xs.Session.AuthCookie]")
|
||||
return err
|
||||
}
|
||||
rec.SetAuthCookie(tmp)
|
||||
|
||||
log.Printf("[xs.Session: op:%c who:%s connhost:%s cmd:%s auth:****]\n",
|
||||
rec.Op()[0], string(rec.Who()), string(rec.ConnHost()), string(rec.Cmd()))
|
||||
|
||||
var valid bool
|
||||
var allowedCmds string // Currently unused
|
||||
if xs.AuthUserByToken(xs.NewAuthCtx(), string(rec.Who()), string(rec.ConnHost()), string(rec.AuthCookie(true))) {
|
||||
valid = true
|
||||
} else {
|
||||
if useSystemPasswd {
|
||||
//var passErr error
|
||||
valid, _ /*passErr*/ = xs.VerifyPass(xs.NewAuthCtx(), string(rec.Who()), string(rec.AuthCookie(true)))
|
||||
} else {
|
||||
valid, allowedCmds = xs.AuthUserByPasswd(xs.NewAuthCtx(), string(rec.Who()), string(rec.AuthCookie(true)), "/etc/xs.passwd")
|
||||
}
|
||||
}
|
||||
|
||||
_ = loginTimeout.Stop()
|
||||
// Security scrub
|
||||
rec.ClearAuthCookie()
|
||||
|
||||
// Tell client if auth was valid
|
||||
if valid {
|
||||
hc.Write([]byte{1}) // nolint: gosec,errcheck
|
||||
} else {
|
||||
logger.LogNotice(fmt.Sprintln("Invalid user", string(rec.Who()))) // nolint: errcheck,gosec
|
||||
hc.Write([]byte{0}) // nolint: gosec,errcheck
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[allowedCmds:%s]\n", allowedCmds)
|
||||
|
||||
if rec.Op()[0] == 'A' {
|
||||
// Generate automated login token
|
||||
addr := hc.RemoteAddr()
|
||||
hname := goutmp.GetHost(addr.String())
|
||||
logger.LogNotice(fmt.Sprintf("[Generating autologin token for [%s@%s]]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
token := GenAuthToken(string(rec.Who()), string(rec.ConnHost()))
|
||||
tokenCmd := fmt.Sprintf("echo \"%s\" | tee -a ~/.xs_id", token)
|
||||
cmdStatus, runErr := runShellAs(string(rec.Who()), hname, string(rec.TermType()), tokenCmd, false, hc, chaffEnabled)
|
||||
// Returned hopefully via an EOF or exit/logout;
|
||||
// Clear current op so user can enter next, or EOF
|
||||
rec.SetOp([]byte{0})
|
||||
if runErr != nil {
|
||||
logger.LogErr(fmt.Sprintf("[Error generating autologin token for %s@%s]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
} else {
|
||||
log.Printf("[Autologin token generation completed for %s@%s, status %d]\n", rec.Who(), hname, cmdStatus)
|
||||
hc.SetStatus(xsnet.CSOType(cmdStatus))
|
||||
}
|
||||
} else if rec.Op()[0] == 'c' {
|
||||
// Non-interactive command
|
||||
addr := hc.RemoteAddr()
|
||||
hname := goutmp.GetHost(addr.String())
|
||||
logger.LogNotice(fmt.Sprintf("[Running command for [%s@%s]]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
cmdStatus, runErr := runShellAs(string(rec.Who()), hname, string(rec.TermType()), string(rec.Cmd()), false, hc, chaffEnabled)
|
||||
// Returned hopefully via an EOF or exit/logout;
|
||||
// Clear current op so user can enter next, or EOF
|
||||
rec.SetOp([]byte{0})
|
||||
if runErr != nil {
|
||||
logger.LogErr(fmt.Sprintf("[Error spawning cmd for %s@%s]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
} else {
|
||||
logger.LogNotice(fmt.Sprintf("[Command completed for %s@%s, status %d]\n", rec.Who(), hname, cmdStatus)) // nolint: gosec,errcheck
|
||||
hc.SetStatus(xsnet.CSOType(cmdStatus))
|
||||
}
|
||||
} else if rec.Op()[0] == 's' {
|
||||
// Interactive session
|
||||
addr := hc.RemoteAddr()
|
||||
hname := goutmp.GetHost(addr.String())
|
||||
logger.LogNotice(fmt.Sprintf("[Running shell for [%s@%s]]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
|
||||
cmdStatus, runErr := runShellAs(string(rec.Who()), hname, string(rec.TermType()), string(rec.Cmd()), true, hc, chaffEnabled)
|
||||
// Returned hopefully via an EOF or exit/logout;
|
||||
// Clear current op so user can enter next, or EOF
|
||||
rec.SetOp([]byte{0})
|
||||
if runErr != nil {
|
||||
Log.Err(fmt.Sprintf("[Error spawning shell for %s@%s]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
} else {
|
||||
logger.LogNotice(fmt.Sprintf("[Shell completed for %s@%s, status %d]\n", rec.Who(), hname, cmdStatus)) // nolint: gosec,errcheck
|
||||
hc.SetStatus(xsnet.CSOType(cmdStatus))
|
||||
}
|
||||
} else if rec.Op()[0] == 'D' {
|
||||
// File copy (destination) operation - client copy to server
|
||||
log.Printf("[Client->Server copy]\n")
|
||||
addr := hc.RemoteAddr()
|
||||
hname := goutmp.GetHost(addr.String())
|
||||
logger.LogNotice(fmt.Sprintf("[Running copy for [%s@%s]]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
cmdStatus, runErr := runClientToServerCopyAs(string(rec.Who()), string(rec.TermType()), hc, string(rec.Cmd()), chaffEnabled)
|
||||
// Returned hopefully via an EOF or exit/logout;
|
||||
// Clear current op so user can enter next, or EOF
|
||||
rec.SetOp([]byte{0})
|
||||
if runErr != nil {
|
||||
logger.LogErr(fmt.Sprintf("[Error running cp for %s@%s]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
} else {
|
||||
logger.LogNotice(fmt.Sprintf("[Command completed for %s@%s, status %d]\n", rec.Who(), hname, cmdStatus)) // nolint: gosec,errcheck
|
||||
}
|
||||
// TODO: Test this with huge files.. see Bug #22 - do we need to
|
||||
// sync w/sender (client) that we've gotten all data?
|
||||
hc.SetStatus(xsnet.CSOType(cmdStatus))
|
||||
|
||||
// Send CSOExitStatus *before* client closes channel
|
||||
s := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(s, cmdStatus)
|
||||
log.Printf("** cp writing closeStat %d at Close()\n", cmdStatus)
|
||||
hc.WritePacket(s, xsnet.CSOExitStatus) // nolint: gosec,errcheck
|
||||
} else if rec.Op()[0] == 'S' {
|
||||
// File copy (src) operation - server copy to client
|
||||
log.Printf("[Server->Client copy]\n")
|
||||
addr := hc.RemoteAddr()
|
||||
hname := goutmp.GetHost(addr.String())
|
||||
logger.LogNotice(fmt.Sprintf("[Running copy for [%s@%s]]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
cmdStatus, runErr := runServerToClientCopyAs(string(rec.Who()), string(rec.TermType()), hc, string(rec.Cmd()), chaffEnabled)
|
||||
if runErr != nil {
|
||||
logger.LogErr(fmt.Sprintf("[Error spawning cp for %s@%s]\n", rec.Who(), hname)) // nolint: gosec,errcheck
|
||||
} else {
|
||||
// Returned hopefully via an EOF or exit/logout;
|
||||
logger.LogNotice(fmt.Sprintf("[Command completed for %s@%s, status %d]\n", rec.Who(), hname, cmdStatus)) // nolint: gosec,errcheck
|
||||
}
|
||||
// HACK: Bug #22: (xc) Need to wait for rcvr to get final data
|
||||
// TODO: Await specific msg from client to inform they have gotten all data from the tarpipe
|
||||
time.Sleep(time.Duration(900 * time.Millisecond)) // Let rcvr set this on setup?
|
||||
|
||||
// Clear current op so user can enter next, or EOF
|
||||
rec.SetOp([]byte{0})
|
||||
hc.SetStatus(xsnet.CSOType(cmdStatus))
|
||||
//fmt.Println("Waiting for EOF from other end.")
|
||||
//_, _ = hc.Read(nil /*ackByte*/)
|
||||
//fmt.Println("Got remote end ack.")
|
||||
} else {
|
||||
logger.LogErr(fmt.Sprintln("[Bad xs.Session]")) // nolint: gosec,errcheck
|
||||
}
|
||||
return
|
||||
}(&conn) // nolint: errcheck
|
||||
} // Accept() success
|
||||
} //endfor
|
||||
//logger.LogNotice(fmt.Sprintln("[Exiting]")) // nolint: gosec,errcheck
|
||||
}
|
||||
17
xsnet/Makefile
Normal file
17
xsnet/Makefile
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
.PHONY: info clean lib
|
||||
|
||||
all: lib
|
||||
|
||||
clean:
|
||||
go clean .
|
||||
|
||||
lib: info
|
||||
go install .
|
||||
|
||||
ifneq ($(MSYSTEM),)
|
||||
info:
|
||||
@echo "Building for Windows (MSYS)"
|
||||
else
|
||||
info:
|
||||
@echo "Building for Linux"
|
||||
endif
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
package hkexsh
|
||||
package xsnet
|
||||
|
||||
// Copyright (c) 2017-2018 Russell Magee
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
|
|
@ -19,34 +19,47 @@ import (
|
|||
"fmt"
|
||||
"hash"
|
||||
"log"
|
||||
"math/big"
|
||||
|
||||
"blitter.com/go/cryptmt"
|
||||
"github.com/aead/chacha20/chacha"
|
||||
"golang.org/x/crypto/blowfish"
|
||||
"golang.org/x/crypto/twofish"
|
||||
|
||||
// hash algos must be manually imported thusly:
|
||||
// (Would be nice if the golang pkg docs were more clear
|
||||
// on this...)
|
||||
_ "crypto/sha256"
|
||||
_ "crypto/sha512"
|
||||
)
|
||||
|
||||
// Available ciphers for hkex.Conn
|
||||
const (
|
||||
CAlgAES256 = iota
|
||||
CAlgTwofish128 // golang.org/x/crypto/twofish
|
||||
CAlgBlowfish64 // golang.org/x/crypto/blowfish
|
||||
CAlgNoneDisallowed
|
||||
)
|
||||
|
||||
// Available HMACs for hkex.Conn (TODO: not currently used)
|
||||
const (
|
||||
HmacSHA256 = iota
|
||||
HmacNoneDisallowed
|
||||
)
|
||||
// Expand keymat, if necessary, to a minimum of 2x(blocksize).
|
||||
// Keymat is used for initial key and the IV, hence the 2x.
|
||||
// This is occasionally necessary for smaller modes of KEX algorithms
|
||||
// (eg., KEX_HERRADURA256); perhaps an indication these should be
|
||||
// avoided in favour of larger modes.
|
||||
//
|
||||
// This is used for block ciphers; stream ciphers should do their
|
||||
// own key expansion.
|
||||
func expandKeyMat(keymat []byte, blocksize int) []byte {
|
||||
if len(keymat) < 2*blocksize {
|
||||
halg := crypto.SHA256
|
||||
mc := halg.New()
|
||||
if !halg.Available() {
|
||||
log.Fatal("hash not available!")
|
||||
}
|
||||
_, _ = mc.Write(keymat)
|
||||
var xpand []byte
|
||||
xpand = mc.Sum(xpand)
|
||||
keymat = append(keymat, xpand...)
|
||||
log.Println("[NOTE: keymat short - applying key expansion using SHA256]")
|
||||
}
|
||||
return keymat
|
||||
}
|
||||
|
||||
/* Support functionality to set up encryption after a channel has
|
||||
been negotiated via hkexnet.go
|
||||
been negotiated via xsnet.go
|
||||
*/
|
||||
func (hc Conn) getStream(keymat *big.Int) (rc cipher.Stream, mc hash.Hash, err error) {
|
||||
func (hc *Conn) getStream(keymat []byte) (rc cipher.Stream, mc hash.Hash, err error) {
|
||||
var key []byte
|
||||
var block cipher.Block
|
||||
var iv []byte
|
||||
|
|
@ -57,23 +70,24 @@ func (hc Conn) getStream(keymat *big.Int) (rc cipher.Stream, mc hash.Hash, err e
|
|||
// is >= 2*cipher.BlockSize (enough for both key and iv)
|
||||
switch copts {
|
||||
case CAlgAES256:
|
||||
key = keymat.Bytes()[0:aes.BlockSize]
|
||||
keymat = expandKeyMat(keymat, aes.BlockSize)
|
||||
key = keymat[0:aes.BlockSize]
|
||||
block, err = aes.NewCipher(key)
|
||||
ivlen = aes.BlockSize
|
||||
iv = keymat.Bytes()[aes.BlockSize : aes.BlockSize+ivlen]
|
||||
iv = keymat[aes.BlockSize : aes.BlockSize+ivlen]
|
||||
rc = cipher.NewOFB(block, iv)
|
||||
log.Printf("[cipher AES_256 (%d)]\n", copts)
|
||||
break
|
||||
case CAlgTwofish128:
|
||||
key = keymat.Bytes()[0:twofish.BlockSize]
|
||||
keymat = expandKeyMat(keymat, twofish.BlockSize)
|
||||
key = keymat[0:twofish.BlockSize]
|
||||
block, err = twofish.NewCipher(key)
|
||||
ivlen = twofish.BlockSize
|
||||
iv = keymat.Bytes()[twofish.BlockSize : twofish.BlockSize+ivlen]
|
||||
iv = keymat[twofish.BlockSize : twofish.BlockSize+ivlen]
|
||||
rc = cipher.NewOFB(block, iv)
|
||||
log.Printf("[cipher TWOFISH_128 (%d)]\n", copts)
|
||||
break
|
||||
case CAlgBlowfish64:
|
||||
key = keymat.Bytes()[0:blowfish.BlockSize]
|
||||
keymat = expandKeyMat(keymat, blowfish.BlockSize)
|
||||
key = keymat[0:blowfish.BlockSize]
|
||||
block, err = blowfish.NewCipher(key)
|
||||
ivlen = blowfish.BlockSize
|
||||
// N.b. Bounds enforcement of differing cipher algorithms
|
||||
|
|
@ -85,10 +99,24 @@ func (hc Conn) getStream(keymat *big.Int) (rc cipher.Stream, mc hash.Hash, err e
|
|||
//
|
||||
// I assume the other two check bounds and only
|
||||
// copy what's needed whereas blowfish does no such check.
|
||||
iv = keymat.Bytes()[blowfish.BlockSize : blowfish.BlockSize+ivlen]
|
||||
iv = keymat[blowfish.BlockSize : blowfish.BlockSize+ivlen]
|
||||
rc = cipher.NewOFB(block, iv)
|
||||
log.Printf("[cipher BLOWFISH_64 (%d)]\n", copts)
|
||||
break
|
||||
case CAlgCryptMT1:
|
||||
rc = cryptmt.New(nil, nil, keymat)
|
||||
log.Printf("[cipher CRYPTMT1 (%d)]\n", copts)
|
||||
case CAlgChaCha20_12:
|
||||
keymat = expandKeyMat(keymat, chacha.KeySize)
|
||||
key = keymat[0:chacha.KeySize]
|
||||
ivlen = chacha.INonceSize
|
||||
iv = keymat[chacha.KeySize : chacha.KeySize+ivlen]
|
||||
rc, err = chacha.NewCipher(iv, key, chacha.INonceSize)
|
||||
if err != nil {
|
||||
log.Printf("[ChaCha20 config error]\n")
|
||||
fmt.Printf("[ChaCha20 config error]\n")
|
||||
}
|
||||
// TODO: SetCounter() to something derived from key or nonce or extra keymat?
|
||||
log.Printf("[cipher CHACHA20_12 (%d)]\n", copts)
|
||||
default:
|
||||
log.Printf("[invalid cipher (%d)]\n", copts)
|
||||
fmt.Printf("DOOFUS SET A VALID CIPHER ALG (%d)\n", copts)
|
||||
|
|
@ -105,7 +133,13 @@ func (hc Conn) getStream(keymat *big.Int) (rc cipher.Stream, mc hash.Hash, err e
|
|||
if !halg.Available() {
|
||||
log.Fatal("hash not available!")
|
||||
}
|
||||
break
|
||||
case HmacSHA512:
|
||||
log.Printf("[hash HmacSHA512 (%d)]\n", hopts)
|
||||
halg := crypto.SHA512
|
||||
mc = halg.New()
|
||||
if !halg.Available() {
|
||||
log.Fatal("hash not available!")
|
||||
}
|
||||
default:
|
||||
log.Printf("[invalid hmac (%d)]\n", hopts)
|
||||
fmt.Printf("DOOFUS SET A VALID HMAC ALG (%d)\n", hopts)
|
||||
124
xsnet/consts.go
Normal file
124
xsnet/consts.go
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
// consts.go - consts for xsnet
|
||||
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
package xsnet
|
||||
|
||||
// KEX algorithm values
|
||||
//
|
||||
// Specified (in string form) as the extensions parameter
|
||||
// to xsnet.Dial()
|
||||
// Alg is sent in a uint8 so there are up to 256 possible
|
||||
const (
|
||||
KEX_HERRADURA256 = iota // this MUST be first for default if omitted in ctor
|
||||
KEX_HERRADURA512
|
||||
KEX_HERRADURA1024
|
||||
KEX_HERRADURA2048
|
||||
KEX_resvd4
|
||||
KEX_resvd5
|
||||
KEX_resvd6
|
||||
KEX_resvd7
|
||||
KEX_KYBER512
|
||||
KEX_KYBER768
|
||||
KEX_KYBER1024
|
||||
KEX_resvd11
|
||||
KEX_NEWHOPE
|
||||
KEX_NEWHOPE_SIMPLE // 'NewHopeLP-Simple' - https://eprint.iacr.org/2016/1157
|
||||
KEX_resvd14
|
||||
KEX_resvd15
|
||||
KEX_FRODOKEM_1344AES
|
||||
KEX_FRODOKEM_1344SHAKE
|
||||
KEX_FRODOKEM_976AES
|
||||
KEX_FRODOKEM_976SHAKE
|
||||
KEX_invalid = 255
|
||||
)
|
||||
|
||||
// Sent from client to server in order to specify which
|
||||
// algo shall be used (see xsnet.KEX_HERRADURA256, ...)
|
||||
type KEXAlg uint8
|
||||
|
||||
// Extended exit status codes - indicate comm/pty issues
|
||||
// rather than remote end normal UNIX exit codes
|
||||
const (
|
||||
CSENone = 1024 + iota
|
||||
CSETruncCSO // No CSOExitStatus in payload
|
||||
CSEStillOpen // Channel closed unexpectedly
|
||||
CSEExecFail // cmd.Start() (exec) failed
|
||||
CSEPtyExecFail // pty.Start() (exec w/pty) failed
|
||||
CSEPtyGetNameFail // failed to obtain pty name
|
||||
CSEKEXAlgDenied // server rejected proposed KEX alg
|
||||
CSECipherAlgDenied // server rejected proposed Cipher alg
|
||||
CSEHMACAlgDenied // server rejected proposed HMAC alg
|
||||
)
|
||||
|
||||
// Extended (>255 UNIX exit status) codes
|
||||
// This indicate channel-related or internal errors
|
||||
type CSExtendedCode uint32
|
||||
|
||||
// Channel Status/Op bytes - packet types
|
||||
const (
|
||||
// Main connection/session control
|
||||
CSONone = iota // No error, normal packet
|
||||
CSOHmacInvalid // HMAC mismatch detected on remote end
|
||||
CSOTermSize // set term size (rows:cols)
|
||||
CSOExitStatus // Remote cmd exit status
|
||||
CSOChaff // Dummy packet, do not pass beyond decryption
|
||||
|
||||
// Client side errors
|
||||
CSOLoginTimeout
|
||||
|
||||
// Tunnel setup/control/status
|
||||
CSOTunSetup // client -> server tunnel setup request (dstport)
|
||||
CSOTunSetupAck // server -> client tunnel setup ack
|
||||
CSOTunRefused // server -> client: tunnel rport connection refused
|
||||
CSOTunData // packet contains tunnel data [rport:data]
|
||||
CSOTunKeepAlive // client tunnel heartbeat
|
||||
CSOTunDisconn // server -> client: tunnel rport disconnected
|
||||
CSOTunHangup // client -> server: tunnel lport hung up
|
||||
)
|
||||
|
||||
// TunEndpoint.tunCtl control values - used to control workers for client
|
||||
// or server tunnels depending on the code
|
||||
const (
|
||||
TunCtl_Client_Listen = 'a'
|
||||
// [CSOTunAccept]
|
||||
// status: server has ack'd tun setup request
|
||||
// action: client should accept (after re-listening, if required) on lport
|
||||
|
||||
TunCtl_Server_Dial = 'd' // server has dialled OK, client side can accept() conns
|
||||
// [CSOTunAccept]
|
||||
// status: client wants to open tunnel to rport
|
||||
// action:server side should dial() rport on client's behalf
|
||||
)
|
||||
|
||||
// Channel status Op byte type (see CSONone, ... and CSENone, ...)
|
||||
type CSOType uint32
|
||||
|
||||
//TODO: this should be small (max unfragmented packet size?)
|
||||
const MAX_PAYLOAD_LEN = 2*1024*1024*1024 - 1
|
||||
|
||||
// Session symmetric crypto algs
|
||||
const (
|
||||
CAlgAES256 = iota
|
||||
CAlgTwofish128 // golang.org/x/crypto/twofish
|
||||
CAlgBlowfish64 // golang.org/x/crypto/blowfish
|
||||
CAlgCryptMT1 //cryptmt using mtwist64
|
||||
CAlgChaCha20_12
|
||||
CAlgNoneDisallowed
|
||||
)
|
||||
|
||||
// Available ciphers for hkex.Conn
|
||||
type CSCipherAlg uint32
|
||||
|
||||
// Session packet auth HMAC algs
|
||||
const (
|
||||
HmacSHA256 = iota
|
||||
HmacSHA512
|
||||
HmacNoneDisallowed
|
||||
)
|
||||
|
||||
// Available HMACs for hkex.Conn
|
||||
type CSHmacAlg uint32
|
||||
129
xsnet/kcp.go
Normal file
129
xsnet/kcp.go
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
package xsnet
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"blitter.com/go/xs/logger"
|
||||
kcp "github.com/xtaci/kcp-go"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
const (
|
||||
KCP_NONE = iota
|
||||
KCP_AES
|
||||
KCP_BLOWFISH
|
||||
KCP_CAST5
|
||||
KCP_SM4
|
||||
KCP_SALSA20
|
||||
KCP_SIMPLEXOR
|
||||
KCP_TEA
|
||||
KCP_3DES
|
||||
KCP_TWOFISH
|
||||
KCP_XTEA
|
||||
)
|
||||
|
||||
// for github.com/xtaci/kcp-go BlockCrypt alg selection
|
||||
type KCPAlg uint8
|
||||
|
||||
var (
|
||||
kcpKeyBytes []byte = []byte("SET THIS") // symmetric crypto key for KCP (github.com/xtaci/kcp-go) if used
|
||||
kcpSaltBytes []byte = []byte("ALSO SET THIS")
|
||||
)
|
||||
|
||||
func getKCPalgnum(extensions []string) (k KCPAlg) {
|
||||
k = KCP_AES // default
|
||||
var s string
|
||||
for _, s = range extensions {
|
||||
switch s {
|
||||
case "KCP_NONE":
|
||||
k = KCP_NONE
|
||||
break //golint:ignore SA4011 out of for
|
||||
case "KCP_AES":
|
||||
k = KCP_AES
|
||||
break //out of for
|
||||
case "KCP_BLOWFISH":
|
||||
k = KCP_BLOWFISH
|
||||
break //out of for
|
||||
case "KCP_CAST5":
|
||||
k = KCP_CAST5
|
||||
break //out of for
|
||||
case "KCP_SM4":
|
||||
k = KCP_SM4
|
||||
break //out of for
|
||||
case "KCP_SALSA20":
|
||||
k = KCP_SALSA20
|
||||
break //out of for
|
||||
case "KCP_SIMPLEXOR":
|
||||
k = KCP_SIMPLEXOR
|
||||
break //out of for
|
||||
case "KCP_TEA":
|
||||
k = KCP_TEA
|
||||
break //out of for
|
||||
case "KCP_3DES":
|
||||
k = KCP_3DES
|
||||
break //out of for
|
||||
case "KCP_TWOFISH":
|
||||
k = KCP_TWOFISH
|
||||
break //out of for
|
||||
case "KCP_XTEA":
|
||||
k = KCP_XTEA
|
||||
break //out of for
|
||||
}
|
||||
}
|
||||
logger.LogDebug(fmt.Sprintf("[KCP BlockCrypt '%s' activated]", s))
|
||||
return
|
||||
}
|
||||
|
||||
func SetKCPKeyAndSalt(key []byte, salt []byte) {
|
||||
kcpKeyBytes = key
|
||||
kcpSaltBytes = salt
|
||||
}
|
||||
|
||||
func _newKCPBlockCrypt(key []byte, extensions []string) (b kcp.BlockCrypt, e error) {
|
||||
switch getKCPalgnum(extensions) {
|
||||
case KCP_NONE:
|
||||
return kcp.NewNoneBlockCrypt(key)
|
||||
case KCP_AES:
|
||||
return kcp.NewAESBlockCrypt(key)
|
||||
case KCP_BLOWFISH:
|
||||
return kcp.NewBlowfishBlockCrypt(key)
|
||||
case KCP_CAST5:
|
||||
return kcp.NewCast5BlockCrypt(key)
|
||||
case KCP_SM4:
|
||||
return kcp.NewSM4BlockCrypt(key)
|
||||
case KCP_SALSA20:
|
||||
return kcp.NewSalsa20BlockCrypt(key)
|
||||
case KCP_SIMPLEXOR:
|
||||
return kcp.NewSimpleXORBlockCrypt(key)
|
||||
case KCP_TEA:
|
||||
return kcp.NewTEABlockCrypt(key)
|
||||
case KCP_3DES:
|
||||
return kcp.NewTripleDESBlockCrypt(key)
|
||||
case KCP_TWOFISH:
|
||||
return kcp.NewTwofishBlockCrypt(key)
|
||||
case KCP_XTEA:
|
||||
return kcp.NewXTEABlockCrypt(key)
|
||||
}
|
||||
return nil, errors.New("Invalid KCP BlockCrypto specified")
|
||||
}
|
||||
|
||||
func kcpDial(ipport string, extensions []string) (c net.Conn, err error) {
|
||||
kcpKey := pbkdf2.Key(kcpKeyBytes, kcpSaltBytes, 1024, 32, sha1.New)
|
||||
block, be := _newKCPBlockCrypt([]byte(kcpKey), extensions)
|
||||
_ = be
|
||||
return kcp.DialWithOptions(ipport, block, 10, 3)
|
||||
}
|
||||
|
||||
func kcpListen(ipport string, extensions []string) (l net.Listener, err error) {
|
||||
kcpKey := pbkdf2.Key(kcpKeyBytes, kcpSaltBytes, 1024, 32, sha1.New)
|
||||
block, be := _newKCPBlockCrypt([]byte(kcpKey), extensions)
|
||||
_ = be
|
||||
return kcp.ListenWithOptions(ipport, block, 10, 3)
|
||||
}
|
||||
|
||||
func (hl *HKExListener) AcceptKCP() (c net.Conn, e error) {
|
||||
return hl.l.(*kcp.Listener).AcceptKCP()
|
||||
}
|
||||
1588
xsnet/net.go
Normal file
1588
xsnet/net.go
Normal file
File diff suppressed because it is too large
Load diff
418
xsnet/tun.go
Normal file
418
xsnet/tun.go
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
// hkextun.go - Tunnel setup using an established xsnet.Conn
|
||||
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
// golang implementation by Russ Magee (rmagee_at_gmail.com)
|
||||
|
||||
package xsnet
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"blitter.com/go/xs/logger"
|
||||
)
|
||||
|
||||
type (
|
||||
// Tunnels
|
||||
// --
|
||||
// 1. client is given (lport, remhost, rport) by local user
|
||||
// 2. client sends [CSOTunReq:rport] to server
|
||||
// client=> [CSOTunReq:rport] =>remhost
|
||||
//
|
||||
// remhost starts worker to receive/send data using rport
|
||||
// remhost replies to client with rport to acknowledge tun is ready
|
||||
// client<= [CSOTunAck:rport] <=remhost
|
||||
// ... or if rhost rport refuses connection, sends
|
||||
// [CSOTunRefused:rport]
|
||||
//
|
||||
// client starts worker to receive/send data using lport
|
||||
// ... client disconnects: sends remhost [CSOTunClose:rport]
|
||||
// ... or server disconnects: sends client [CSOTunClose:lport]
|
||||
// server at any time sends [CSOTunRefused:rport] if daemon died
|
||||
// --
|
||||
|
||||
// TunEndpoint [securePort:peer:dataPort]
|
||||
TunEndpoint struct {
|
||||
Rport uint16 // Names are from client's perspective
|
||||
Lport uint16 // ... ie., RPort is on server, LPort is on client
|
||||
Peer string //net.Addr
|
||||
Died bool // set by client upon receipt of a CSOTunDisconn
|
||||
KeepAlive uint32 // must be reset by client to keep server dial() alive
|
||||
Ctl chan rune //See TunCtl_* consts
|
||||
Data chan []byte
|
||||
}
|
||||
)
|
||||
|
||||
func (hc *Conn) CollapseAllTunnels(client bool) {
|
||||
for k, t := range *hc.tuns {
|
||||
var tunDst bytes.Buffer
|
||||
binary.Write(&tunDst, binary.BigEndian, t.Lport)
|
||||
binary.Write(&tunDst, binary.BigEndian, t.Rport)
|
||||
if client {
|
||||
hc.WritePacket(tunDst.Bytes(), CSOTunHangup)
|
||||
} else {
|
||||
hc.WritePacket(tunDst.Bytes(), CSOTunDisconn)
|
||||
}
|
||||
delete(*hc.tuns, k)
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *Conn) InitTunEndpoint(lp uint16, p string /* net.Addr */, rp uint16) {
|
||||
hc.Lock()
|
||||
defer hc.Unlock()
|
||||
if (*hc.tuns) == nil {
|
||||
(*hc.tuns) = make(map[uint16]*TunEndpoint)
|
||||
}
|
||||
if (*hc.tuns)[rp] == nil {
|
||||
var addrs []net.Addr
|
||||
if p == "" {
|
||||
addrs, _ = net.InterfaceAddrs()
|
||||
p = addrs[0].String()
|
||||
}
|
||||
(*hc.tuns)[rp] = &TunEndpoint{ /*Status: CSOTunSetup,*/ Peer: p,
|
||||
Lport: lp, Rport: rp, Data: make(chan []byte, 1),
|
||||
Ctl: make(chan rune, 1)}
|
||||
logger.LogDebug(fmt.Sprintf("InitTunEndpoint [%d:%s:%d]", lp, p, rp))
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("InitTunEndpoint [reusing] %v", (*hc.tuns)[rp]))
|
||||
if (*hc.tuns)[rp].Data == nil {
|
||||
// When re-using a tunnel it will have its
|
||||
// data channel removed on closure. Re-create it
|
||||
(*hc.tuns)[rp].Data = make(chan []byte, 1)
|
||||
}
|
||||
(*hc.tuns)[rp].KeepAlive = 0
|
||||
(*hc.tuns)[rp].Died = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (hc *Conn) StartClientTunnel(lport, rport uint16) {
|
||||
hc.InitTunEndpoint(lport, "", rport)
|
||||
|
||||
go func() {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for cmd := range (*hc.tuns)[rport].Ctl {
|
||||
if cmd == 'a' {
|
||||
l, e := net.Listen("tcp4", fmt.Sprintf(":%d", lport))
|
||||
if e != nil {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] Could not get lport %d! (%s)", lport, e))
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] Listening for client tunnel port %d", lport))
|
||||
|
||||
for {
|
||||
c, e := l.Accept() // blocks until new conn
|
||||
// If tunnel is being re-used, re-init it
|
||||
if (*hc.tuns)[rport] == nil {
|
||||
hc.InitTunEndpoint(lport, "", rport)
|
||||
}
|
||||
// ask server to dial() its side, rport
|
||||
var tunDst bytes.Buffer
|
||||
binary.Write(&tunDst, binary.BigEndian, lport)
|
||||
binary.Write(&tunDst, binary.BigEndian, rport)
|
||||
hc.WritePacket(tunDst.Bytes(), CSOTunSetup)
|
||||
|
||||
if e != nil {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] Accept() got error(%v), hanging up.", e))
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] Accepted tunnel client %v", (*hc.tuns)[rport]))
|
||||
|
||||
// outside client -> tunnel lport
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if c.Close() != nil {
|
||||
logger.LogDebug("[ClientTun] worker A: conn c already closed")
|
||||
} else {
|
||||
logger.LogDebug("[ClientTun] worker A: closed conn c")
|
||||
}
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
logger.LogDebug("[ClientTun] worker A: starting")
|
||||
|
||||
var tunDst bytes.Buffer
|
||||
binary.Write(&tunDst, binary.BigEndian, lport)
|
||||
binary.Write(&tunDst, binary.BigEndian, rport)
|
||||
for {
|
||||
rBuf := make([]byte, 1024)
|
||||
//Read data from c, encrypt/write via hc to client(lport)
|
||||
c.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
|
||||
n, e := c.Read(rBuf)
|
||||
if e != nil {
|
||||
if e == io.EOF {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] worker A: lport Disconnected: shutting down tunnel %v", (*hc.tuns)[rport]))
|
||||
// if Died was already set, server-side already is gone.
|
||||
if hc.TunIsAlive(rport) {
|
||||
hc.WritePacket(tunDst.Bytes(), CSOTunHangup)
|
||||
}
|
||||
hc.ShutdownTun(rport) // FIXME: race-C
|
||||
break
|
||||
} else if strings.Contains(e.Error(), "i/o timeout") {
|
||||
if !hc.TunIsAlive(rport) {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] worker A: timeout: Server side died, hanging up %v", (*hc.tuns)[rport]))
|
||||
hc.ShutdownTun(rport)
|
||||
break
|
||||
}
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] worker A: Read error from lport of tun %v\n%s", (*hc.tuns)[rport], e))
|
||||
if hc.TunIsAlive(rport) {
|
||||
hc.WritePacket(tunDst.Bytes(), CSOTunHangup)
|
||||
}
|
||||
hc.ShutdownTun(rport)
|
||||
break
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
rBuf = append(tunDst.Bytes(), rBuf[:n]...)
|
||||
_, de := hc.WritePacket(rBuf[:n+4], CSOTunData)
|
||||
if de != nil {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] worker A: Error writing to tunnel %v, %s]\n", (*hc.tuns)[rport], de))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.LogDebug("[ClientTun] worker A: exiting")
|
||||
}()
|
||||
|
||||
// tunnel lport -> outside client (c)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if c.Close() != nil {
|
||||
logger.LogDebug("[ClientTun] worker B: conn c already closed")
|
||||
} else {
|
||||
logger.LogDebug("[ClientTun] worker B: closed conn c")
|
||||
}
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
logger.LogDebug("[ClientTun] worker B: starting")
|
||||
|
||||
for {
|
||||
bytes, ok := <-(*hc.tuns)[rport].Data // FIXME: race-C w/ShutdownTun calls
|
||||
if ok {
|
||||
c.SetWriteDeadline(time.Now().Add(200 * time.Millisecond))
|
||||
_, e := c.Write(bytes)
|
||||
if e != nil {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] worker B: lport conn closed"))
|
||||
break
|
||||
}
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("[ClientTun] worker B: Channel was closed?"))
|
||||
break
|
||||
}
|
||||
}
|
||||
logger.LogDebug("[ClientTun] worker B: exiting")
|
||||
}()
|
||||
|
||||
} // end Accept() worker block
|
||||
wg.Wait()
|
||||
|
||||
// When both workers have exited due to a disconnect or other
|
||||
// condition, it's safe to remove the tunnel descriptor.
|
||||
logger.LogDebug("[ClientTun] workers exited")
|
||||
hc.ShutdownTun(rport)
|
||||
} // end for-accept
|
||||
} // end Listen() block
|
||||
}
|
||||
} // end t.Ctl for
|
||||
}()
|
||||
}
|
||||
|
||||
func (hc *Conn) AgeTunnel(endp uint16) uint32 {
|
||||
hc.Lock()
|
||||
defer hc.Unlock()
|
||||
(*hc.tuns)[endp].KeepAlive += 1
|
||||
return (*hc.tuns)[endp].KeepAlive
|
||||
}
|
||||
|
||||
func (hc *Conn) ResetTunnelAge(endp uint16) {
|
||||
hc.Lock()
|
||||
defer hc.Unlock()
|
||||
(*hc.tuns)[endp].KeepAlive = 0
|
||||
}
|
||||
|
||||
func (hc *Conn) TunIsNil(endp uint16) bool {
|
||||
hc.Lock()
|
||||
defer hc.Unlock()
|
||||
return (*hc.tuns)[endp] == nil
|
||||
}
|
||||
|
||||
func (hc *Conn) TunIsAlive(endp uint16) bool {
|
||||
hc.Lock()
|
||||
defer hc.Unlock()
|
||||
return !(*hc.tuns)[endp].Died
|
||||
}
|
||||
|
||||
func (hc *Conn) MarkTunDead(endp uint16) {
|
||||
hc.Lock()
|
||||
defer hc.Unlock()
|
||||
(*hc.tuns)[endp].Died = true
|
||||
}
|
||||
|
||||
func (hc *Conn) ShutdownTun(endp uint16) {
|
||||
hc.Lock()
|
||||
defer hc.Unlock()
|
||||
if (*hc.tuns)[endp] != nil {
|
||||
(*hc.tuns)[endp].Died = true
|
||||
if (*hc.tuns)[endp].Data != nil {
|
||||
close((*hc.tuns)[endp].Data)
|
||||
(*hc.tuns)[endp].Data = nil
|
||||
}
|
||||
}
|
||||
delete((*hc.tuns), endp)
|
||||
}
|
||||
|
||||
func (hc *Conn) StartServerTunnel(lport, rport uint16) {
|
||||
hc.InitTunEndpoint(lport, "", rport)
|
||||
var err error
|
||||
|
||||
go func() {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
//
|
||||
// worker to age server tunnel and kill it if keepalives
|
||||
// stop from client
|
||||
//
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if hc.TunIsNil(rport) {
|
||||
logger.LogDebug("[ServerTun] worker A: Client endpoint removed.")
|
||||
break
|
||||
}
|
||||
age := hc.AgeTunnel(rport)
|
||||
if age > 25 {
|
||||
hc.MarkTunDead(rport)
|
||||
logger.LogDebug("[ServerTun] worker A: Client died, hanging up.")
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for cmd := range (*hc.tuns)[rport].Ctl {
|
||||
var c net.Conn
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] got Ctl '%c'.", cmd))
|
||||
if cmd == 'd' {
|
||||
// if re-using tunnel, re-init it
|
||||
if hc.TunIsNil(rport) {
|
||||
hc.InitTunEndpoint(lport, "", rport)
|
||||
}
|
||||
logger.LogDebug("[ServerTun] dialling...")
|
||||
c, err = net.Dial("tcp4", fmt.Sprintf(":%d", rport))
|
||||
if err != nil {
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] Dial() error for tun %v: %s", (*hc.tuns)[rport], err))
|
||||
var resp bytes.Buffer
|
||||
binary.Write(&resp, binary.BigEndian /*lport*/, uint16(0))
|
||||
binary.Write(&resp, binary.BigEndian, rport)
|
||||
hc.WritePacket(resp.Bytes(), CSOTunRefused)
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] Tunnel Opened - %v", (*hc.tuns)[rport]))
|
||||
var resp bytes.Buffer
|
||||
binary.Write(&resp, binary.BigEndian, lport)
|
||||
binary.Write(&resp, binary.BigEndian, rport)
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] Writing CSOTunSetupAck %v", (*hc.tuns)[rport]))
|
||||
hc.WritePacket(resp.Bytes(), CSOTunSetupAck)
|
||||
|
||||
//
|
||||
// worker to read data from the rport (to encrypt & send to client)
|
||||
//
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer func() {
|
||||
logger.LogDebug("[ServerTun] worker A: deferred hangup")
|
||||
if c.Close() != nil {
|
||||
logger.LogDebug("[ServerTun] workerA: conn c already closed")
|
||||
}
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
logger.LogDebug("[ServerTun] worker A: starting")
|
||||
|
||||
var tunDst bytes.Buffer
|
||||
binary.Write(&tunDst, binary.BigEndian, (*hc.tuns)[rport].Lport)
|
||||
binary.Write(&tunDst, binary.BigEndian, (*hc.tuns)[rport].Rport)
|
||||
for {
|
||||
rBuf := make([]byte, 1024)
|
||||
// Read data from c, encrypt/write via hc to client(lport)
|
||||
c.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
|
||||
n, e := c.Read(rBuf)
|
||||
if e != nil {
|
||||
if e == io.EOF {
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] worker A: rport Disconnected: shutting down tunnel %v", (*hc.tuns)[rport]))
|
||||
if hc.TunIsAlive(rport) {
|
||||
hc.WritePacket(tunDst.Bytes(), CSOTunDisconn)
|
||||
}
|
||||
hc.ShutdownTun(rport) // FIXME: race-A
|
||||
break
|
||||
} else if strings.Contains(e.Error(), "i/o timeout") {
|
||||
if !hc.TunIsAlive(rport) {
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] worker A: timeout: Server side died, hanging up %v", (*hc.tuns)[rport]))
|
||||
hc.ShutdownTun(rport) // FIXME: race-B
|
||||
break
|
||||
}
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] worker A: Read error from rport of tun %v: %s", (*hc.tuns)[rport], e))
|
||||
if hc.TunIsAlive(rport) {
|
||||
hc.WritePacket(tunDst.Bytes(), CSOTunDisconn)
|
||||
}
|
||||
hc.ShutdownTun(rport) // FIXME: race-C
|
||||
break
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
rBuf = append(tunDst.Bytes(), rBuf[:n]...)
|
||||
hc.WritePacket(rBuf[:n+4], CSOTunData)
|
||||
}
|
||||
}
|
||||
logger.LogDebug("[ServerTun] worker A: exiting")
|
||||
}()
|
||||
|
||||
// worker to read data from client (already decrypted) & fwd to rport
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer func() {
|
||||
logger.LogDebug("[ServerTun] worker B: deferred hangup")
|
||||
if c.Close() != nil {
|
||||
logger.LogDebug("[ServerTun] worker B: conn c already closed")
|
||||
}
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
logger.LogDebug("[ServerTun] worker B: starting")
|
||||
for {
|
||||
rData, ok := <-(*hc.tuns)[rport].Data // FIXME: race-A, race-B, race-C (w/ShutdownTun() calls)
|
||||
if ok {
|
||||
c.SetWriteDeadline(time.Now().Add(200 * time.Millisecond))
|
||||
_, e := c.Write(rData)
|
||||
if e != nil {
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] worker B: ERROR writing to rport conn"))
|
||||
break
|
||||
}
|
||||
} else {
|
||||
logger.LogDebug(fmt.Sprintf("[ServerTun] worker B: Channel was closed?"))
|
||||
break
|
||||
}
|
||||
}
|
||||
logger.LogDebug("[ServerTun] worker B: exiting")
|
||||
}()
|
||||
wg.Wait()
|
||||
} // end if Dialled successfully
|
||||
delete((*hc.tuns), rport)
|
||||
}
|
||||
} // t.Ctl read loop
|
||||
logger.LogDebug("[ServerTun] Tunnel exiting t.Ctl read loop - channel closed??")
|
||||
}()
|
||||
}
|
||||
16
xspasswd/Makefile
Normal file
16
xspasswd/Makefile
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
.PHONY: clean all vis lint
|
||||
|
||||
EXTPKGS = bytes,errors,flag,fmt,internal,io,log,net,os,path,runtime,time,strings,sync,syscall,binary,encoding
|
||||
EXE = $(notdir $(shell pwd))
|
||||
|
||||
all:
|
||||
go build $(BUILDOPTS) .
|
||||
|
||||
clean:
|
||||
$(RM) $(EXE) $(EXE).exe
|
||||
|
||||
vis:
|
||||
go-callvis -format png -file xspasswd-vis -ignore $(EXTPKGS) -group pkg,type .
|
||||
|
||||
lint:
|
||||
-golangci-lint run
|
||||
BIN
xspasswd/xspasswd-vis.png
Normal file
BIN
xspasswd/xspasswd-vis.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
|
|
@ -1,7 +1,7 @@
|
|||
// Util to generate/store passwords for users in a file akin to /etc/passwd
|
||||
// suitable for the demo hkexsh server, using bcrypt.
|
||||
//
|
||||
// Copyright (c) 2017-2018 Russell Magee
|
||||
// Copyright (c) 2017-2020 Russell Magee
|
||||
// Licensed under the terms of the MIT license (see LICENSE.mit in this
|
||||
// distribution)
|
||||
//
|
||||
|
|
@ -16,37 +16,50 @@ import (
|
|||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/user"
|
||||
|
||||
xs "blitter.com/go/xs"
|
||||
"github.com/jameskeane/bcrypt"
|
||||
hkexsh "blitter.com/go/hkexsh"
|
||||
)
|
||||
|
||||
var (
|
||||
version string
|
||||
gitCommit string
|
||||
)
|
||||
|
||||
// nolint: gocyclo
|
||||
func main() {
|
||||
var vopt bool
|
||||
var pfName string
|
||||
var newpw string
|
||||
var confirmpw string
|
||||
var userName string
|
||||
|
||||
flag.BoolVar(&vopt, "v", false, "show version")
|
||||
flag.StringVar(&userName, "u", "", "username")
|
||||
flag.StringVar(&pfName, "f", "/etc/hkexsh.passwd", "passwd file")
|
||||
flag.StringVar(&pfName, "f", "/etc/xs.passwd", "passwd file")
|
||||
flag.Parse()
|
||||
|
||||
if vopt {
|
||||
fmt.Printf("version %s (%s)\n", version, gitCommit)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
var uname string
|
||||
if len(userName) == 0 {
|
||||
log.Println("specify username with -u")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
u, err := user.Lookup(userName)
|
||||
if err != nil {
|
||||
log.Printf("Invalid user %s\n", userName)
|
||||
log.Fatal(err)
|
||||
}
|
||||
uname = u.Username
|
||||
//u, err := user.Lookup(userName)
|
||||
//if err != nil {
|
||||
// log.Printf("Invalid user %s\n", userName)
|
||||
// log.Fatal(err)
|
||||
//}
|
||||
//uname = u.Username
|
||||
uname = userName
|
||||
|
||||
fmt.Printf("New Password:")
|
||||
ab, err := hkexsh.ReadPassword(int(os.Stdin.Fd()))
|
||||
ab, err := xs.ReadPassword(os.Stdin.Fd())
|
||||
fmt.Printf("\r\n")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
|
@ -55,7 +68,7 @@ func main() {
|
|||
newpw = string(ab)
|
||||
|
||||
fmt.Printf("Confirm:")
|
||||
ab, err = hkexsh.ReadPassword(int(os.Stdin.Fd()))
|
||||
ab, err = xs.ReadPassword(os.Stdin.Fd())
|
||||
fmt.Printf("\r\n")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
|
@ -84,7 +97,7 @@ func main() {
|
|||
}
|
||||
//fmt.Println("Salt:", salt, "Hash:", hash)
|
||||
|
||||
b, err := ioutil.ReadFile(pfName)
|
||||
b, err := ioutil.ReadFile(pfName) // nolint: gosec
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
|
@ -92,15 +105,18 @@ func main() {
|
|||
|
||||
r.Comma = ':'
|
||||
r.Comment = '#'
|
||||
r.FieldsPerRecord = 4 // username:salt:authCookie:disallowedCmdList (a,b,...)
|
||||
r.FieldsPerRecord = 3 // username:salt:authCookie [TODO:disallowedCmdList (a,b,...)]
|
||||
|
||||
records, err := r.ReadAll()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for i, _ := range records {
|
||||
|
||||
recFound := false
|
||||
for i := range records {
|
||||
//fmt.Println(records[i])
|
||||
if records[i][0] == uname {
|
||||
recFound = true
|
||||
records[i][1] = salt
|
||||
records[i][2] = hash
|
||||
}
|
||||
|
|
@ -109,16 +125,26 @@ func main() {
|
|||
// records[i][0] = "#" + records[i][0]
|
||||
//}
|
||||
}
|
||||
if !recFound {
|
||||
newRec := []string{uname, salt, hash}
|
||||
records = append(records, newRec)
|
||||
}
|
||||
|
||||
outFile, err := ioutil.TempFile("", "hkexsh-passwd")
|
||||
outFile, err := ioutil.TempFile("", "xs-passwd")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
w := csv.NewWriter(outFile)
|
||||
w.Comma = ':'
|
||||
//w.FieldsPerRecord = 4 // username:salt:authCookie:disallowedCmdList (a,b,...)
|
||||
w.Write([]string{"#username", "salt", "authCookie", "disallowedCmdList"})
|
||||
w.WriteAll(records)
|
||||
err = w.Write([]string{"#username", "salt", "authCookie" /*, "disallowedCmdList"*/})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
err = w.WriteAll(records)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err = w.Error(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue