ssh_pub_key.py 1.01 KB
Newer Older
Kevin Morris's avatar
Kevin Morris committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os
import tempfile

from subprocess import PIPE, Popen

from sqlalchemy.orm import backref, mapper, relationship

from aurweb.models.user import User
from aurweb.schema import SSHPubKeys


class SSHPubKey:
    def __init__(self, **kwargs):
        self.UserID = kwargs.get("UserID")
        self.Fingerprint = kwargs.get("Fingerprint")
        self.PubKey = kwargs.get("PubKey")


def get_fingerprint(pubkey):
    with tempfile.TemporaryDirectory() as tmpdir:
        pk = os.path.join(tmpdir, "ssh.pub")

        with open(pk, "w") as f:
            f.write(pubkey)

        proc = Popen(["ssh-keygen", "-l", "-f", pk], stdout=PIPE, stderr=PIPE)
        out, err = proc.communicate()

        # Invalid SSH Public Key. Return None to the caller.
        if proc.returncode != 0:
            return None

        parts = out.decode().split()
        fp = parts[1].replace("SHA256:", "")

    return fp


mapper(SSHPubKey, SSHPubKeys, properties={
    "User": relationship(User, backref=backref("ssh_pub_key", uselist=False))
})