Commit 03670d78 authored by Johannes Schilling's avatar Johannes Schilling
Browse files

initial commit, working version

parents
/pcidentd
MIT License
Copyright (c) 2017 Johannes Schilling <of82ecuq@cip.cs.fau.de>
Copyright (c) 2017 Simon Ruderich <he29heri@cip.cs.fau.de>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
pcidentd
========
A *P*rivacy *C*onserving Ident Daemon.
Uses HMAC with uid and requesting server domain (without subdomains) to generate
a per-domain unique ident response. If no reverse DNS is available for a
requesting server, no domain is part of ident response generation; i.e. for all
such servers the response will be the same for a specific user.
USAGE
-----
Generate a secret key for HMAC, e.g. by running
```
head -c 64 /dev/urandom > secret
```
Then start pcidentd with `-hmacSecretFile path/to/secret`.
LICENSE
-------
pcidentd is licensed under the MIT license, see COPYING.
/*
MIT License
Copyright (c) 2017 Johannes Schilling <of82ecuq@cip.cs.fau.de>
Copyright (c) 2017 Simon Ruderich <he29heri@cip.cs.fau.de>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package main
import (
"bufio"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"regexp"
"strconv"
"strings"
)
const (
MacBytes = 8 // how many bytes of the hash we send in the ident response
)
func main() {
hmacSecretFile := flag.String("hmacSecretFile",
"/etc/pcidentd/hmac.secret",
"file in which the hmac secret is stored")
flag.Parse()
// setup hmac secret from file
f, err := os.Open(*hmacSecretFile)
if err != nil {
log.Fatalf("unable to open secrets file: %v", err)
}
hmacSecret, err := ioutil.ReadAll(f)
if err != nil {
log.Fatalf("unable to read HMAC secret: %v", err)
}
// warn if hmac file has insecure permissions
s, err := f.Stat()
if err != nil {
log.Fatalf("unable to fstat secrets file: %v", err)
}
if s.Mode().Perm()&0077 != 0 {
log.Fatalf("insecure permissions of secrets file")
}
f.Close()
l, err := net.Listen("tcp", ":ident")
if err != nil {
log.Fatalf("error listening: %v", err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Fatalf("error accepting: %v", err)
}
go func() {
defer func() {
err := recover()
if err != nil {
log.Println(err)
}
conn.Close()
}()
err := handleIdentRequest(conn, hmacSecret)
if err != nil {
log.Println(err)
}
}()
}
}
var requestLineRegex = regexp.MustCompile(`^([0-9]+)\s*,\s*([0-9]+)\r?\n$`)
func handleIdentRequest(c net.Conn, hmacSecret []byte) error {
line, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
return err
}
matches := requestLineRegex.FindStringSubmatch(line)
// matches is [orig, firstGroup, secondGroup] if matched
// else empty
if len(matches) != 3 {
return fmt.Errorf("malformed request line: %q", line)
}
lPort, err := parsePort(matches[1])
if err != nil {
return err
}
rPort, err := parsePort(matches[2])
if err != nil {
return err
}
// don't need to check error because it's what go library just gave us
rIPstr, _, _ := net.SplitHostPort(c.RemoteAddr().String())
rIP := net.ParseIP(rIPstr)
tcpPath := "/proc/net/tcp"
if rIP.To4() == nil {
tcpPath = "/proc/net/tcp6"
}
uid, err := GetUidForLocalPort(tcpPath, lPort, rPort, rIP)
if err != nil {
return err
}
if uid == "" {
// we return UNKNOWN-ERROR instead of NO-USER for even more privacy
_, err = fmt.Fprintf(c, "%d,%d:ERROR:UNKNOWN-ERROR\n", lPort, rPort)
return err
}
// idea: have the same ident accross multiple servers of the same network
// (e.g. foo.freenode.net, bar.freenode.net, ..), so we make the domain
// without subdomains part of the hmac sum.
guessedDomain, err := guessRemoteAddrDomain(rIPstr)
if err != nil {
log.Printf("reverse lookup failed for %v: %v", rIPstr, err)
// if reverse dns fails for our peer, we must use a stable identifier.
// this makes the ident string for one user for all hosts without
// reverse dns the same, but can't be helped really
guessedDomain = ""
}
// use hmac, because plain hash would allow local users to brute force ident
// response (i.e. reverse lookup)
mac := hmac.New(sha256.New, hmacSecret)
fmt.Fprintln(mac, uid)
fmt.Fprintln(mac, guessedDomain)
macB64 := base64.StdEncoding.EncodeToString(mac.Sum(nil))
_, err = fmt.Fprintf(c, "%d,%d:USERID:OTHER:%s\n",
lPort, rPort, macB64[:MacBytes])
if err != nil {
return err
}
return nil
}
func guessRemoteAddrDomain(rIPstr string) (string, error) {
hostnames, err := net.LookupAddr(rIPstr)
if err != nil {
return "", err
}
parts := strings.Split(hostnames[0], ".")
n := len(parts)
// just tld?
if n < 3 {
return hostnames[0], nil
}
return strings.Join(parts[n-3:], "."), nil
}
func parsePort(in string) (int, error) {
p, err := strconv.ParseUint(in, 10, 16)
return int(p), err
}
/*
MIT License
Copyright (c) 2017 Johannes Schilling <of82ecuq@cip.cs.fau.de>
Copyright (c) 2017 Simon Ruderich <he29heri@cip.cs.fau.de>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// endianness!! (/proc/net/tcp "parsing")
// +build amd64, 386
package main
import (
"bufio"
"encoding/hex"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
)
var colSplitRegex = regexp.MustCompile(`\s+`)
func GetUidForLocalPort(lookupPath string, identLPort, identRPort int, identRIP net.IP) (string, error) {
f, err := os.Open(lookupPath)
if err != nil {
return "", err
}
defer f.Close()
s := bufio.NewScanner(f)
s.Scan() // skip the headers line
for s.Scan() {
l := strings.TrimSpace(s.Text())
parts := colSplitRegex.Split(l, -1)
local := strings.Split(parts[1], ":")
remote := strings.Split(parts[2], ":")
uid := parts[7]
lPort, err := hexToPort(local[1])
if err != nil {
return "", err
}
rIP, err := hexToIp(remote[0])
if err != nil {
return "", err
}
rPort, err := hexToPort(remote[1])
if err != nil {
return "", err
}
if lPort == identLPort && rPort == identRPort && rIP.Equal(identRIP) {
return uid, nil
}
}
return "", nil
}
func hexToIp(in string) (net.IP, error) {
switch len(in) {
case 8:
return hexToIp4(in)
case 32:
return hexToIp6(in)
default:
return nil, fmt.Errorf("hexToIp: invalid ip address %q", in)
}
}
func hexToIp4(in string) (net.IP, error) {
ip, err := hex.DecodeString(in)
if err != nil {
return nil, err
}
// reverse order because endianness
// TODO: if this ever gets ported to big endian, make do with another workaround
ip[0], ip[1], ip[2], ip[3] = ip[3], ip[2], ip[1], ip[0]
return ip, nil
}
func hexToIp6(in string) (net.IP, error) {
// idea: one v6 addr is actually just 4 v4 addrs (if you squint hard enough)
var ip []byte
for i := 0; i < 32; i += 8 {
x, err := hexToIp4(in[i : i+8])
if err != nil {
return nil, err
}
ip = append(ip, x...)
}
return ip, nil
}
func hexToPort(in string) (int, error) {
x, err := strconv.ParseUint(in, 16, 16)
return int(x), err
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment