How come I cannot set multiple cookies - openresty

I'm trying to set multiple cookies, but it's not working:
if type(ngx.header["Set-Cookie"]) ~= "table" then
ngx.header["Set-Cookie"] = {}
end
table.insert(ngx.header["Set-Cookie"], "Cookie1=abc; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie2=def; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie3=ghi; Path=/")
On the client I do not receive any cookies.

ngx.header["Set-Cookie"] is a special table, and must be reassigned to with a new table every time you modify it (elements inserted or removed from it have no effect on the cookies that will be sent to the client):
if type(ngx.header["Set-Cookie"]) == "table" then
ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", unpack(ngx.header["Set-Cookie"]) }
else
ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", ngx.header["Set-Cookie"] }
end

You can use https://github.com/cloudflare/lua-resty-cookie
local ck = require "resty.cookie"
local cookie, err = ck:new()
cookie:set({key = "Cookie1", value = "abc", path = "/"})
cookie:set({key = "Cookie2", value = "def", path = "/"})
cookie:set({key = "Cookie3", value = "ghi", path = "/"})

Related

OpenIO swift deny host headers

OpenIO 7.2.0.
I have an OpenIO with keystone (queens) auth cluster.
By default any user can configure his own acls and public url.
I would like to restrict user only for read and write in containers and objects.
Apparently deny_host_headers can do the job in proxy-server.conf but it not seems to be working -> nothing append.
I didn't find any "super admin" acls.
Any idea ?
My proxy-server.conf ->
# OpenIO managed
[DEFAULT]
use_stderr = False
bind_ip = ip
bind_port = port
workers = 72
max_clients = 1024
user = openio
log_facility = /dev/log
log_header = true
log_level = INFO
log_name = OIO,OPENIO,oioswift,0
eventlet_debug = false
sds_namespace = OPENIO
sds_proxy_url = http://ip:port
sds_default_account = openio
sds_connection_timeout = 5
sds_read_timeout = 35
sds_write_timeout = 35
sds_pool_connections = 500
sds_pool_maxsize = 500
sds_max_retries = 0
sds_tls = False
[pipeline:main]
pipeline = catch_errors gatekeeper healthcheck proxy-logging cache bulk proxy-logging authtoken keystoneauth proxy-logging copy container-quotas account-quotas slo dlo versioned_writes proxy-logging proxy-server
[filter:catch_errors]
use = egg:swift#catch_errors
[filter:gatekeeper]
use = egg:swift#gatekeeper
[filter:healthcheck]
use = egg:oioswift#healthcheck
[filter:proxy-logging]
use = egg:swift#proxy_logging
access_log_headers = false
access_log_headers_only =
[filter:cache]
use = egg:swift#memcache
memcache_servers = ip:port
memcache_max_connections = 10
oio_cache = False
oio_cache_ttl = 0
[filter:bulk]
use = egg:swift#bulk
#[filter:tempurl]
#use = egg:swift#tempurl
#[filter:swift3]
#use = egg:swift3#swift3
#force_swift_request_proxy_log = True
#s3_acl = True
#check_bucket_owner = True
#location = us-east-1
#max_bucket_listing = 1000
#max_multi_delete_objects = 1000
#max_upload_part_num = 10000
#log_s3api_command = False
#bucket_db_enabled = True
#bucket_db_prefix = s3bucket:
#storage_domain = s3.openio.io
#bucket_db_master_name = OPENIO-master-1
#bucket_db_sentinel_hosts = ip:port
#[filter:tempauth]
#use = egg:oioswift#tempauth
#user_demo_demo = DEMO_PASS .admin
[filter:copy]
use = egg:oioswift#copy
object_post_as_copy = False
[filter:container-quotas]
use = egg:swift#container_quotas
[filter:account-quotas]
use = egg:swift#account_quotas
[filter:slo]
use = egg:oioswift#slo
max_manifest_segments = 10000
concurrency = 10
[filter:dlo]
use = egg:swift#dlo
[filter:versioned_writes]
use = egg:oioswift#versioned_writes
allow_versioned_writes = True
[app:proxy-server]
use = egg:oioswift#main
object_post_as_copy = False
allow_account_management = True
account_autocreate = True
sds_chunk_checksum_algo =
deny_host_headers = x-container-sync-key, x-container-sync-to, x-account-meta-temp-url-key, x-account-meta-temp-url-key-2, x-container-meta-temp-url-key, x-container-meta-temp-url-key-2, x-account-access-control
[filter:authtoken]
auth_type = password
#username = swift
username = user
project_name = user
region_name = region
user_domain_id = domain
memcache_secret_key = memcache_secret_key
paste.filter_factory = keystonemiddleware.auth_token:filter_factory
insecure = True
cache = swift.cache
delay_auth_decision = True
token_cache_time = 300
auth_url = http://ip:port
include_service_catalog = False
www_authenticate_uri = http://ip:port
memcached_servers = ip:port
password = password
revocation_cache_time = 60
memcache_security_strategy = ENCRYPT
project_domain_id = dommain
[filter:keystoneauth]
use = egg:swift#keystoneauth
operator_roles = role
reseller_admin_role = role
delay_auth_decision = False in authtoken section in proxy-server.conf file do the job.
delay_auth_decision : delay_auth_decision defaults to False, but leaving it as false will prevent other auth systems, staticweb, tempurl, formpost, and ACLs from working. This value must be explicitly set to True.
Now only files owners can view/create/edit containers/objects -> ACLs and sharing won't works.

How to verify PKCS#7 signature in PHP

I have a digital signature (encrypted format PKCS#7) needs to be verified So I have tried by using different PHP core methods(openssl_verify, openssl_pkcs7_verify and even tried by external library such as phpseclib But nothing worked :(
I get a signature along with some extra params through by this link..
http://URL?sign={'param':{'Id':'XXXXXXX','lang':'EN','Rc':'00','Email': 'test#yahoo.com'’},'signature':'DFERVgYJKoZIhvcNAQcCoIIFRzCCBUMCAQExCzAJBgUrDg
MCGgUAMIGCBgkqhkiG9w0BBwGgdQRzeyJEYXRlIjoidG9fY2hhcihzeXNkYXRlJ0RETU1ZWVlZJykgIiwiSWQiOiJ
VMDExODg3NyIsIklkaW9tYSI6IkNBUyIsIk51bUVtcCI6IlUwM23D4DEE3dSi...'}
PHP code - returns always 0(false) instead of 1(true).
$JSONDATA = str_replace("'", '"', #$_GET["sign"]);
$data = json_decode($JSONDATA, true);
$this->email = $data['param']["EMAIL"];
$this->signature = $data['signature'];
$this->signature_base64 = base64_decode($this->signature);
$this->dataencoded = json_encode($data['param']);
//SOLUTION 1 (By using phpseclib) but didnt work..
$rsa = $this->phpseclib->load();
$keysize = 2048;
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$d = $rsa->createKey($keysize);
$Kver = $d['publickey'];
$KSign = $d['privatekey'];
// Signing
$rsa->loadKey($KSign);
$rsa->setSignatureMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setHash('sha256');
$signature = $rsa->sign($this->dataencoded);
$signedHS = base64_encode($signature);
// Verification
$rsa->loadKey($Kver);
$status = $rsa->verify($this->dataencoded, $this->firma_base64); // getting an error on this line Message: Invalid signature
var_dump($status); // reutrn false
//SOLUTION 2 (By using code php methods)
// obtener la clave pública desde el certifiado y prepararla
$orignal_parse = parse_url("https://example.com", PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
openssl_x509_export($cert["options"]["ssl"]["peer_certificate"],$cert_key);
$pubkeyid = openssl_pkey_get_public($cert_key);
$dataencoded = json_encode($data['param']);
echo $ok = openssl_x509_check_private_key($cert_key,$this->firma_base64); // return nothing
echo $ok1 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok2 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
echo $ok3 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok4 = openssl_verify($dataencoded, $this->firma, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
Java code - (this code works and returns true)
private boolean verifySignautre(String frm) throws NetinfException, IOException, CMSException,
CertificateException, OperatorCreationException, Exception {
Security.addProvider(new BouncyCastleProvider());
//we extract the containers that make up the signature and the keystore used to sign included in the same signature.
CMSSignedData signedData = new CMSSignedData(Base64.decode(frm.getBytes()));
SignerInformationStore signers = signedData.getSignerInfos();
Store certStore = signedData.getCertificates();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
//retrieve the certificate with the recipient's id.
SignerInformation signerInfo = (SignerInformation) it.next();
Collection certCollection = certStore.getMatches(signerInfo.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder signerCertificateHolder = (X509CertificateHolder) certIt.next();
//create the container to validate signature.
ContentVerifierProvider contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new
DefaultDigestAlgorithmIdentifierFinder()).build(signerCertificateHolder);
//valid signature and then certificate validity date
try{
X509Certificate signedcert = new
JcaX509CertificateConverter().setProvider("BC").getCertificate(signerCertificateHolder);
signedcert.checkValidity();
signedcert.verify(signedcert.getPublicKey());
return true;
}catch(Exception e){
return false;
}
}
I simply need to convert this Java code into PHP. However, as you can see above that I tried different approaches but none of them worked.
Please support me to find the solution.
your support would be higly appreciated

lua https.request with certificate

I'm trying to make a request on lua with certificate.
Recently I've gotten a COMODO SSL.
I've tried many tutorials on the internet, but to no avail.
I found this blog's proposal very interesting:
I am not getting able to execute the request on Linux/OpenWRT/Lua 5.1.
COMODO has provided me with the following files:
AddTrustExternalCARoot.crt
my_domain_com.crt
COMODORSAAddTrustCA.crt
COMODORSADomainValidationSecureServerCA.crt
And in this blog he mentions these files:
key = "/root/client.key"
certificate="/root/client.crt",
cafile="/root/ca.crt"
How do I convert the COMODO's .crt files the to those mentioned in the blog?
Obs: I tried to download with curl and get, but it did not work.
I've described the details in a blog post; basically, you need to specify the mode and the certificate file for the ssl.wrap call:
local params = {
mode = "client",
protocol = "tlsv1",
cafile = "/path/to/downloaded/cacert.pem", --<-- added cafile parameters
verify = "peer", --<-- changed "none" to "peer"
options = "all",
}
If you need to convert .crt to .pem file, then the following SO answer may help. I haven't tried with .crt, but the examples I have work with .pem files.
I solve it with this code:
module("https", package.seeall)
local socket = require "socket"
local http = require "socket.http"
local ssl = require "ssl"
local ltn12 = require "ltn12"
local try = socket.try
local protect = socket.protect
local DEFAULT_PROTOCOL = "sslv23"
local DEFAULT_CAFILE = "/etc/ssl/certs/ca-certificates.crt"
local DEFAULT_VERIFY = "peer"
local DEFAULT_OPTIONS = "all"
local DEFAULT_CIPHERS = "ADH-AES256-SHA:ADH-AES128-SHA:HIGH:MEDIUM"
local DEFAULT_HTTPS_PORT = 443
local https_mt = {
-- Create proxy functions for each call through the metatable
__index = function(tbl, key)
local f = function(prxy, ...)
local c = prxy.c
return c[key](c, ...)
end
tbl[key] = f -- Save new proxy function in cache for speed
return f
end
}
local function new_create(params)
return function()
local t = { c = try(socket.tcp()) }
function t:connect(host, port)
try(self.c:connect(host, port))
self.c = try(ssl.wrap(self.c, params))
try(self.c:dohandshake())
return 1
end
return setmetatable(t, https_mt)
end
end
local function request_generic(args)
local sslparams = {
mode = "client",
protocol = args.protocol or DEFAULT_PROTOCOL,
cafile = args.cafile or DEFAULT_CAFILE,
verify = args.verify or DEFAULT_VERIFY,
options = args.options or DEFAULT_OPTIONS,
ciphers = args.ciphers or DEFAULT_CIPHERS
}
local req = {
url = args.url,
port = args.port or DEFAULT_HTTPS_PORT,
sink = args.sink,
method = args.method,
headers = args.headers,
source = args.source,
step = args.step,
proxy = args.proxy, -- Buggy?
redirect = args.redirect,
create = new_create(sslparams)
}
return http.request(req)
end
local function request_simple(url, body)
local tbl = { }
local req = {
url = url,
sink = ltn12.sink.table(tbl)
}
if body then
req.method = "POST"
req.source = ltn12.source.string(body)
req.headers = {
["Content-length"] = #body,
["Content-type"] = "application/x-www-form-urlencoded"
}
end
local _, status, headers = request_generic(req)
return table.concat(tbl), status, headers
end
function request(req_or_url, body)
if type(req_or_url) == "string" then
return request_simple(req_or_url, body)
else
return request_generic(req_or_url)
end
end

How to access project name from a query of type portfolioitem

I am trying to match Project name in my query and also trying to print the name of the project associated with each feature record. I know there are plenty of answers but I couldn't find anything that could help me. I am trying to do something like this:
pi_query.type = "portfolioitem"
pi_query.fetch="Name,FormattedID,Owner,c_ScopingTeam,c_AspirationalRelease,c_AssignedProgram,Tags"
#To be configured as per requirement
pi_query.project_scope_up = false
pi_query.project_scope_down = false
pi_query.order = "FormattedID Asc"
pi_query.query_string = "(Project.Name = \"Uni - Serviceability\")"
pi_results = #rally.find(pi_query)
I am trying to match the project name but it simply doesn't work, I also tried printing the name of the project, i tried Project.Name, Project.Values or simply Project. But it doesn't work. I am guessing it is because of my query type which is "portfolioItem" and I can't change my type because I am getting all other attribute values correctly.
Thanks.
Make sure to fetch Project, e.g: feature_query.fetch = "Name,FormattedID,Project"
and this should work:
feature_query.query_string = "(Project.Name = \"My Project\")"
Here is an example where a feature is found by project name.
require 'rally_api'
#Setup custom app information
headers = RallyAPI::CustomHttpHeader.new()
headers.name = "create story in one project, add it to a feature from another project"
headers.vendor = "Nick M RallyLab"
headers.version = "1.0"
# Connection to Rally
config = {:base_url => "https://rally1.rallydev.com/slm"}
config[:username] = "user#co.com"
config[:password] = "secret"
config[:workspace] = "W"
config[:project] = "Product1"
config[:headers] = headers #from RallyAPI::CustomHttpHeader.new()
#rally = RallyAPI::RallyRestJson.new(config)
obj = {}
obj["Name"] = "new story xyz123"
new_s = #rally.create("hierarchicalrequirement", obj)
query = RallyAPI::RallyQuery.new()
query.type = "portfolioitem"
query.fetch = "Name,FormattedID,Project"
query.workspace = {"_ref" => "https://rally1.rallydev.com/slm/webservice/v2.0/workspace/12352608129" }
query.query_string = "(Project.Name = \"Team Group 1\")"
result = #rally.find(query)
feature = result.first
puts feature
field_updates={"PortfolioItem" => feature}
new_s.update(field_updates)

hidden variable in R

I am using the RLastFM package, and have some question about the function:
> tag.getTopArtists
function (tag, key = lastkey, parse = TRUE)
{
params = list(method = "tag.gettopartists", tag = tag, api_key = lastkey)
ret = getForm(baseurl, .params = params)
doc = xmlParse(ret, asText = TRUE)
if (parse)
doc = p.tag.gettopartists(doc)
return(doc)
}
the author included lastkey as the api_key, but I can't find it by using ls(), where is it?
Thanks.
getAnywhere(lastkey) show you where it is and RLastFM:::lastkey gives you this value. The value isn't exported from namespace of package.
For more details check Writing R Extensions manual, Package name spaces section.