stlinkv2.py now works with newer PyUSB
[gnuk/gnuk.git] / tool / gpg_agent.py
1 """
2 gpg_agent.py - a library to connect gpg-agent
3
4 Copyright (C) 2013, 2015 Free Software Initiative of Japan
5 Author: NIIBE Yutaka <gniibe@fsij.org>
6
7 This file is a part of Gnuk, a GnuPG USB Token implementation.
8
9 Gnuk is free software: you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 Gnuk is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
17 License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 """
22
23 import platform, os, socket
24 IS_WINDOWS=(platform.system() == 'Windows')
25
26 BUFLEN=1024
27
28 class gpg_agent(object):
29     def __init__(self):
30         if IS_WINDOWS:
31             home = os.getenv("HOME")
32             if not home:
33                 home = os.getenv("APPDATA")
34             comm_port = os.path.join(home, "gnupg", "S.gpg-agent")
35             #
36             f = open(comm_port, "rb", 0)
37             infostr = f.read().decode('UTF-8')
38             f.close()
39             #
40             info = infostr.split('\n', 1)
41             port = int(info[0])
42             nonce = info[1]
43             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
44             s.connect(("localhost", port))
45             s.send(nonce)
46         else:
47             infostr = os.getenv("GPG_AGENT_INFO")
48             info = infostr.split(':', 2)
49             path = info[0]
50             s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
51             s.connect(path)
52         self.sock = s
53         self.buf_remained = b""
54         self.response = None
55
56     def read_line(self):
57         line = b""
58         if self.buf_remained != b"":
59             chunk = self.buf_remained
60         else:
61             chunk = self.sock.recv(BUFLEN)
62         while True:
63             pos = chunk.find(b'\n')
64             if pos >= 0:
65                 self.buf_remained = chunk[pos+1:]
66                 line = line + chunk[0:pos]
67                 return line
68             else:
69                 line = line + chunk
70                 chunk = self.sock.recv(BUFLEN)
71
72     def get_response(self):
73         r = self.response
74         result = b""
75         while True:
76             i = r.find(b'%')
77             if i < 0:
78                 result += r
79                 break
80             hex_str = r[i+1:i+3].decode('UTF-8')
81             result += r[0:i]
82             if bytes == str:
83                 result += chr(int(hex_str,16))
84             else:
85                 result += bytes.fromhex(hex_str)
86             r = r[i+3:]
87         return result
88
89     def send_command(self, cmd):
90         self.sock.send(cmd.encode('UTF-8'))
91         self.response = b""
92         while True:
93             while True:
94                 l = self.read_line()
95                 if l[0] != b'#'[0]:
96                     break
97             if l[0] == b'D'[0]:
98                 self.response += l[2:]
99             elif l[0:2] == b'OK':
100                 return True
101             elif l[0:3] == b'ERR':
102                 return False
103             else:                    # XXX: S, INQUIRE, END
104                 return False
105
106     def close(self):
107         self.sock.send(b'BYE\n')
108         bye = self.read_line()
109         self.sock.close()
110         return bye              # "OK closing connection"
111
112 # Test
113 if __name__ == '__main__':
114     g = gpg_agent()
115     print(g.read_line().decode('UTF-8'))
116     print(g.send_command("KEYINFO --list --data\n"))
117     kl_str = g.get_response().decode('UTF-8')
118     kl_str = kl_str[0:-1]
119     kl = kl_str.split('\n')
120     import re
121     kl_o3 = [kg for kg in kl if re.search("OPENPGP\\.3", kg)]
122     print(kl_o3)
123     kg = kl_o3[0].split(' ')[0]
124     print(g.send_command("READKEY %s\n" % kg))
125     r = g.get_response()
126     import binascii
127     print(binascii.hexlify(r).decode('UTF-8'))
128     print(g.close().decode('UTF-8'))