summaryrefslogtreecommitdiffstats
path: root/net/src/lib.rs
blob: b0e10a71031783eb05a88c3ebf1001e2bdd0146d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//! For accessing keys over the network.
//!
//! Currently, this module provides access to keyservers providing the [HKP] protocol.
//!
//! [HKP]: https://tools.ietf.org/html/draft-shaw-openpgp-hkp-00
//!
//! # Example
//!
//! We provide a very reasonable default key server backed by
//! `hkps.pool.sks-keyservers.net`, the subset of the [SKS keyserver]
//! network that uses https to protect integrity and confidentiality
//! of the communication with the client:
//!
//! [SKS keyserver]: https://www.sks-keyservers.net/overview-of-pools.php#pool_hkps
//!
//! ```no_run
//! # extern crate openpgp;
//! # extern crate sequoia_core;
//! # extern crate sequoia_net;
//! # use openpgp::types::KeyId;
//! # use sequoia_core::Context;
//! # use sequoia_net::KeyServer;
//! # fn main() {
//! let ctx = Context::new("org.sequoia-pgp.example").unwrap();
//! let mut ks = KeyServer::sks_pool(&ctx).unwrap();
//! let keyid = KeyId::from_hex("31855247603831FD").unwrap();
//! println!("{:?}", ks.get(&keyid));
//! # }
//! ```

extern crate openpgp;
extern crate sequoia_core;

extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate native_tls;
extern crate tokio_core;
#[macro_use]
extern crate percent_encoding;

use percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use self::futures::{Future, Stream};
use self::hyper::client::{FutureResponse, HttpConnector};
use self::hyper::header::{ContentLength, ContentType};
use self::hyper::{Client, Uri, StatusCode, Request, Method};
use self::hyper_tls::HttpsConnector;
use self::native_tls::{Certificate, TlsConnector};
use self::tokio_core::reactor::Core;
use std::convert::From;
use std::io::{Cursor, Read};
use std::io;

use sequoia_core::{Context, NetworkPolicy};
use openpgp::tpk::{self, TPK};
use openpgp::types::KeyId;
use openpgp::{Message, armor};

define_encode_set! {
    /// Encoding used for submitting keys.
    ///
    /// The SKS keyserver as of version 1.1.6 is a bit picky with
    /// respect to the encoding.
    pub KEYSERVER_ENCODE_SET = [DEFAULT_ENCODE_SET] | {'-', '+', '/' }
}

/// For accessing keyservers using HKP.
pub struct KeyServer {
    core: Core,
    client: Box<AClient>,
    uri: Uri,
}

const DNS_WORKER: usize = 4;

impl KeyServer {
    /// Returns a handle for the given URI.
    pub fn new(ctx: &Context, uri: &str) -> Result<Self> {
        let core = Core::new()?;
        let uri: Uri = uri.parse()?;

        let client: Box<AClient> = match uri.scheme() {
            Some("hkp") => Box::new(Client::new(&core.handle())),
            Some("hkps") => {
                Box::new(Client::configure()
                         .connector(HttpsConnector::new(DNS_WORKER,
                                                        &core.handle())?)
                         .build(&core.handle()))
            },
            _ => return Err(Error::MalformedUri),
        };

        Self::make(ctx, core, client, uri)
    }

    /// Returns a handle for the given URI.
    ///
    /// `cert` is used to authenticate the server.
    pub fn with_cert(ctx: &Context, uri: &str, cert: Certificate) -> Result<Self> {
        let core = Core::new()?;
        let uri: Uri = uri.parse()?;

        let client: Box<AClient> = {
            let mut ssl = TlsConnector::builder()?;
            ssl.add_root_certificate(cert)?;
            let ssl = ssl.build()?;

            let mut http = HttpConnector::new(DNS_WORKER, &core.handle());
            http.enforce_http(false);
            Box::new(Client::configure()
                     .connector(HttpsConnector::from((http, ssl)))
                     .build(&core.handle()))
        };

        Self::make(ctx, core, client, uri)
    }

    /// Returns a handle for the SKS keyserver pool.
    ///
    /// The pool `hkps://hkps.pool.sks-keyservers.net` provides HKP
    /// services over https.  It is authenticated using a certificate
    /// included in this library.  It is a good default choice.
    pub fn sks_pool(ctx: &Context) -> Result<Self> {
        let uri = "hkps://hkps.pool.sks-keyservers.net";
        let cert = Certificate::from_der(
            include_bytes!("sks-keyservers.netCA.der")).unwrap();
        Self::with_cert(ctx, uri, cert)
    }

    /// Common code for the above functions.
    fn make(ctx: &Context, core: Core, client: Box<AClient>, uri: Uri) -> Result<Self> {
        let s = uri.scheme().ok_or(Error::MalformedUri)?;
        match s {
            "hkp" => ctx.network_policy().assert(NetworkPolicy::Insecure),
            "hkps" => ctx.network_policy().assert(NetworkPolicy::Encrypted),
            _ => unreachable!()
        }?;
        let uri =
            format!("{}://{}:{}",
                    match s {"hkp" => "http", "hkps" => "https", _ => unreachable!()},
                    uri.host().ok_or(Error::MalformedUri)?,
                    match s {
                        "hkp" => uri.port().or(Some(11371)),
                        "hkps" => uri.port().or(Some(443)),
                        _ => unreachable!(),
                    }.unwrap()).parse()?;

        Ok(KeyServer{core: core, client: client, uri: uri})
    }

    /// Retrieves the key with the given `keyid`.
    pub fn get(&mut self, keyid: &KeyId) -> Result<TPK> {
        let uri = format!("{}/pks/lookup?op=get&options=mr&search=0x{}",
                          self.uri, keyid.as_hex()).parse()?;
        let result = self.core.run(
            self.client.do_get(uri).and_then(|res| {
                let status = res.status();
                res.body().concat2().and_then(move |body| Ok((status, body)))
            }));

        let key: Result<::std::vec::Vec<u8>> = match result {
            Ok((status, body)) =>
                match status {
                    StatusCode::Ok => {
                        let mut c = Cursor::new(body.as_ref());
                        let mut r = armor::Reader::new(&mut c, armor::Kind::PublicKey);
                        let mut key = Vec::new();
                        r.read_to_end(&mut key)?;
                        Ok(key)
                    },
                    StatusCode::NotFound => Err(Error::NotFound),
                    n => Err(Error::from(n)),
                }
            Err(e) => Err(Error::HyperError(e)),
        };

        let m = Message::from_bytes(&key?)?;
        TPK::from_message(m).map_err(|e| </